Handy tips to handle form submit using AJAX

Hello everyone, this time, I am going to explain different ways to handle form submit using AJAX.

Basically, to submit a form via AJAX, we need to follow certain process in our javascript file.

1- Process form submit event
2- Get all the form data using javascript/jQuery
3- Submit the form with data using AJAX
4- Show success/error message according to the result

So, in this blog, we are going to discuss different ways to get all the form data. Lets put some light into there :).

Tip – 1
Get all form data individually and put in key=>value format like below.

var formData = {
    'first_name'  : $('input[name=first_name]').val(),
    'last_name'   : $('input[name=last_name]').val(),
    'dob'         : $('input[name=dob]').val(),
    'gender'      : $('input[name=gender]').val(),
    'email'       : $('input[name=email]').val()
};

In short cut, one can write :

$("#form[name]").each(function(event, obj) {
    formData[obj.name] = $(obj).val();
});

Tip – 2
Instead of getting the data individually, we can use serialize() to get the data in string manner.

var formData = $("#formId").serialize();

The above code will produce the data in string manner i.e.

first_name=Rasmus&last_name=Lerdorf&dob=....

Tip – 3
We can use serializeObject() for serializing the data, which, instead of encoding form elements to string, converts form elements to a valid JSON object.

var formData = $("#formId").serializeObject();

Note: You need to include the below code to use serializeObject().

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

Using the above code, we can access the data using .(dot) operator i.e.

formData.first_name ==> Rasmus

Tip – 4
We also can use serializeArray(), which creates an array of objects (name and value) by serializing form values.

var formData = $("#formId").serializeArray();

After applying seriaizeArray(), we can get the data by looping through it i.e.

$.each(formData, function(event, field){
    $("#results").append(field.name + ":" + field.value + " ");
});

The above will print first_name:Rasmus last_name:Lerdorf dob:….

Tip – 5
We can use HTML5 formData() to achieve the same thing. It allows to compile a set of key/value pairs to send data using XMLHttpRequest.

var formObj = document.querySelector("form");
var formData = new FormData(formObj);

The output data will be in the same format that the form’s submit() method would be.

Okay!! That’s it… One can use any of the way mentioned above for accessing the form data. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and will be happy to listen from you 🙂 :).

HTML5: Geolocation from the ground up

The word Geolocation is the combination of two words Geo (Geographic) and Location. Yes, that means, Geolocation is the way of getting geographic location of the object. It uses the positioning system logic, for getting the location. The HTML Geolocation is secured and that’s the reason, it won’t show the position till user approves for it.

Hmmm… the word Geolocation sounds interesting … right? 🙂 So, why to wait? Lets check deeper part of Geolocation API.

Geolocation has never been part of HTML5 specification, previously called Web Application Specification. It is created by W3C not the WHATWG. We can use geolocation in multiple ways, like –

  • Social networking services for ex-Facebook is using Geolocation extensively, for getting current places, that allow users to share their location to others.
  • It helps user to guide for the direction, they want.
  • Anyone can share their location with others.
  • Users can be aware of what is around them depending upon their interests.

But, let’s think practically, how it is possible to get current location of any person, without using anything ❓ …

Hmmm… :idea:, we just now came across one word “Sharing”, means user need to share his/her location using some API and it might sound like a privacy concern. But, the specification clearly specify that the user have to first allow the user agent so it can share the location with the server.

According to GeoLocation API Specification, “User agents must not send location information to Web sites without the express permission of the user. User agents must acquire permission through a user interface, unless they have prearranged trust relationships with users, as described below. The user interface must include the URI of the document origin.”

When requesting for authorization, the browsers may show alert message to the user. Let’s check how it works with some browsers.

Firefox :-
Screen Shot 2014-11-03 at 6.08.19 pm

Chrome :-
Screen Shot 2014-11-03 at 6.06.38 pm

Safari :-
Screen Shot 2014-11-03 at 6.09.30 pm

Once a user allows the user agent to share the user location with the server, there are still some privacy concerns:

  • What would be the duration of saving location data
  • Will it be shared to other sites or other users
  • What would be the result, if the location data can be deleted/updated by end user

That’s why, according to Geolocation API Specification, “Recipients must clearly and conspicuously disclose the fact that they are collecting location data, the purpose for the collection, how long the data is retained, how the data is secured, how the data is shared if it is shared, how users may access, update and delete the data, and any other choices that users have with respect to the data.”.

According to Geolocation API Specification, “Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input”.

The geolocation API is located in the Geolocation object. There are some methods which are available with Geolocation API, among those, 2 methods (getCurrentPosition() and watchPosition()) are used to get the location of the user.

Let’s check one example with using the above two methods.

<!DOCTYPE html>
<html>
    <head>
        <title>Geolocation API Test</title>
    </head>
    <body onload="getLocation()">
        <script>
            function getLocation() {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(showPosition);
                } else { 
                    alert("Geolocation is not supported by this browser.");
                }
            }

            function showPosition(position) {
                alert("Latitude: " + position.coords.latitude + " - Longitude: " + position.coords.longitude);	
            }
        </script>
    </body>
</html>

getCurrentPosition() :-
It gets the user location only once. It takes 3 parameters i.e. showLocation, ErrorHandler, options.
showLocation => It is the callback method which retrieves the current location of the user. It always called asynchronously and method returns Position as an object. There are few properties present for that Position object.

  • coords.latitude => To get the latitude of the location
  • coords.longitude => To get the longitude of the location
  • coords.accuracy => To get the accuracy of the position returned
  • coords.altitude => To get the altitude of the position above sea level[optional]
  • coords.altitudeAccuracy => To get the accuracy of the altitude position[optional]
  • coords.heading => To get the device current location as per degree, clockwise from North[optional]
  • coords.speed => To get the speed in meter per second[optional]
  • timestamp => To get the timestamp for the response[optional]

ErrorHandler => This is an optional parameter. It invoked when any error occurs while calling PositionError object.
options => This is also an optional parameter. This can contain many options for getting location information like use of the locations which is already in cache, check for the accuracy of the location info, get the timeout info while getting location info.

watchPosition() :-
It regular checks the user location and check if the user location has changed. It also takes 3 parameters i.e. showLocation, ErrorHandler, options, which description we already went through.

This method returns an unique id, which can be used to cancel getting the regular location updates.

clearWatch() :-
There are one more method available clearWatch(), which cancels/stops watching position of the user. It takes one parameter i.e. watchId.
watchId => It is an unique ID of the watchPosition call to cancel the current call.

So, what do you think!! It is nice to use … right? 🙂 Hmmm… yes, using Geolocation API, we can get the geographic location of the user, using which, we can do a lot stuff :).

Note :- Please check here for Browser support details.

Thanks 🙂 and will be happy to listen from you 🙂 :).

HTML5: A multi-threading approach with Web Workers

The word Web Worker specifies a JavaScript running in the background, without affecting the performance of the page, independently of other user-interface scripts that may also have been executed from the same HTML page.

Let’s go into little depth to understand what it exactly means :).

Javascript will hang the browser, where the code written by us requires a high CPU utilization. When executing scripts in a Web page, the page becomes unresponsive until the script is finished and shows “unresponsive script” alert message.

ummm … 😡 we should check one example, to better understand, what I want to say here!!!

<!DOCTYPE HTML>
<html>
    <head>
        <title>Big loop test</title>
        <script>
            function loopTest() {
                for (var i = 0; i <= 10000000000; i++){
                    var j = i;
                }

                alert("Completed " + j + "iterations" );
            }

            function sayTime() {
                var d = new Date();
                var hour = d.getHours();
                var minute = d.getMinutes();
                var second = d.getSeconds();

                alert(hour + ':' + minute + ':' + second);
            }
        </script>
    </head>
    <body>
       <input type="button" onclick="loopTest();" value="Check For Loop" />
       <input type="button" onclick="sayTime();" value="Get Current Time" />
    </body>
</html>

If we run the above code, and click both the button one by one, we will get the following error alert message, as because CPU will be busy running the loop and wait for the completion of that task.

Screen Shot 2014-10-09 at 11.54.21 am

So, what should we do now ❓ … Do we really have any idea, how to fix this type of issue :-(.

Hmmm… 💡 Yes, I guess we can do so using Web Workers 🙂 😎

Web Workers allow for concurrent execution of the browser threads, which will do all the computational tasks without interrupting the user interface and run on separate/different threads. That means, we can continue to do whatever we want: clicking, selecting things, loading images etc., while the web worker runs in the background.

Sounds interesting 😎 🙂

Process :-
Web workers interact with the main document via message passing. The following code illustrates about how Web Worker works.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Big for loop</title>
        <script>
            var worker = new Worker('checkLoop.js');

            if(typeof(Worker) !== "undefined") {
                worker.onmessage = function (event) {
                    alert("Completed " + event.data + "iterations" );
                };

                function sayTime() {
                    var d = new Date();
                    var hour = d.getHours();
                    var minute = d.getMinutes();
                    var second = d.getSeconds();

                    alert(hour + ':' + minute + ':' + second);
                }
            } else {
                alert('Your browser does not support Web Worker');
            } 

            
        </script>
    </head>
    <body>
       <input type="button" onclick="sayTime();" value="Get Current Time"/>
    </body>
</html>

checkLoop.js

for (var i = 0; i <= 1000000000; i++){
   var j = i;
}
postMessage(j);

if(typeof(Worker) !== "undefined") { ... }

This code checks for the Browser support of Web Worker.

var worker = new Worker('checkLoop.js');

This code is used for initializing Web Worker with the URL of a JavaScript file, which contains the code the worker will execute. If the specified javascript file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. If the path does not found, the worker will fail silently.

worker.onmessage = function (event) { ... }

This code sets event listeners and communicates with the script that spawned it from the main page.

Terminate a Web Worker :-

worker.terminate();

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated. So, need to use the above code to terminate a Web Worker.

Reuse the Web Worker :-

worker = undefined;

If you set the worker variable to undefined, after it has been terminated, you can reuse the code.

Note :- Since web workers are in external files, they do not have access to the following JavaScript objects.

  • Parent Object
  • Window Object
  • Document Object

Note :- Please check here for Browser support details.

Thanks 🙂 and will be happy to listen from you 🙂 :).

HTML5: Use of MathML – A better way to present mathematical notation

The word MathML represents Mathematical Markup Language, which means a language which designed to present and capture mathematics for Web.

In computer language,

MathML is an XML application for describing Mathematical notation and capturing both the structure and content. The goal of MathML is to enable Mathematics to be served, received and processed in WWW.

MathML elements can be used inside HTML5 document using <math>...</math> tags.

Ummm… 😐 difficult to understand the theory… me too :(.

So, let’s check one example for our clarification :-

Example – 1

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title>Binomial Theorem</title>
    </head>
    <body>
        <p>Binomial Theorem:</p>
        <math xmlns="http://www.w3.org/1998/Math/MathML">
            <mrow>
                <msup>
                    <mfenced>
                        <mrow>
                            <mi>a</mi>
                            <mo>+</mo>
                            <mi>b</mi>
                        </mrow>
                    </mfenced>
                    <mn>2</mn>
                </msup>
                <mo>=</mo>
                <msup>
                    <mrow>
                        <mi>a</mi>
                    </mrow>
                    <mn>2</mn>
                </msup>
                <mo>+</mo>
                <msup>
                    <mrow>
                        <mi>b</mi>
                    </mrow>
                    <mn>2</mn>
                </msup>
                <mo>+</mo>
                <mrow>
                    <mn>2</mn>
                    <mi>a</mi>
                    <mi>b</mi>
                </mrow>
            </mrow> 
        </math>
    </body>
</html>

This would produce the following output :-
Screen Shot 2014-10-03 at 6.04.35 pm

Wonderful 😯 … This is really nice :eek:. Using the above markup language, we can create any mathematical notation. 🙂 Great !!!

The above code contains some tags, which might be unknown for some of us. So, let’s analyze those and put some light on those tags for better understanding.

  1. <mrow> : horizontal row of items
  2. <msup>, <munderover> : superscripts, limits over and under operators like sums, etc.
  3. <mfrac> : mathematical fractions
  4. <msqrt> and <mroot> : roots
  5. <mfenced> : surrounding content with fences, such as parentheses.
  6. <mi>x<mi> : mathematical identifiers
  7. <mo>+</mo> : mathematical operators
  8. <mn>2</mn> : mathematical numbers
  9. <mtext>non zero</mtext> : mathematical text

😎 Let’s check some more example and that should be little critical ones ;-).

Example – 2

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title>Quadratic Formula</title>
    </head>

    <body>
        <p>Quadratic Formula:</p>
        <math xmlns="http://www.w3.org/1998/Math/MathML">
            <mrow>
                <mi>x</mi>
                <mo>=</mo>
                <mfrac>
                    <mrow>
                        <mo form="prefix">-</mo>
                        <mi>b</mi>
                        <mo>±<!-- &amp;PlusMinus; --></mo>
                        <msqrt>
                            <msup>
                                <mi>b</mi>
                                <mn>2</mn>
                            </msup>
                            <mo>-</mo>
                            <mn>4</mn>
                            <mi>a</mi>
                            <mi>c</mi>
                        </msqrt>
                    </mrow>
                    <mrow>
                        <mn>2</mn>
                        <mi>a</mi>
                    </mrow>
                </mfrac>
            </mrow>
        </math>
    </body>
</html>

This would produce the following output :-
Screen Shot 2014-10-03 at 7.22.44 pm

Example – 3

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <title>Matrix Example</title>
        
        <style>
            body {
                margin-left: 10%;
                margin-top: 5%;
            }
        </style>
    </head>

    <body>
        <p>Matrix Example:</p>

        <math xmlns="http://www.w3.org/1998/Math/MathML">
            <mrow>
                <mfenced open="(" close=")">
                    <mtable>
                        <mtr>
                           <mtd><mi>1</mi></mtd>
                           <mtd><mi>5</mi></mtd>
                           <mtd><mi>3</mi></mtd>
                        </mtr>
                        <mtr>
                           <mtd><mi>8</mi></mtd>
                           <mtd><mi>2</mi></mtd>
                           <mtd><mi>6</mi></mtd>
                        </mtr>
                        <mtr>
                           <mtd><mi>7</mi></mtd>
                           <mtd><mi>9</mi></mtd>
                           <mtd><mi>0</mi></mtd>
                        </mtr>
                    </mtable>
                </mfenced>
            </mrow>
        </math>
    </body>
</html>

This would produce the following output :-
Screen Shot 2014-10-03 at 7.55.46 pm

Great !!! 🙂 😎 Very interesting one :). We can do any mathematical notation with MathML.

Note: Please check here for Browser support details.

Thanks 🙂 and will be happy to listen from you 🙂 :).

HTML5: Use of picture element for responsive image design

The word Responsive, itself suggest a technique for providing flexible UI for different view-ports. The Responsive Design allows designers or developers to build website that adapt to every screen size, in result, it should responds to the needs of the users and the devices they are using. Adapting Responsive Web Design, developers or designers will get a strategic solution for performance issue, starts from excessive downloads of images, JavaScript and CSS and HTML. The main advantage is – the layout changes based on the size and capabilities of the device.

For example – on a phablet, users would see the content with a single column view, on a tablet, it might show the same content in two columns and on a lappy, the same might show in more than two columns.

But, let me think, why I am discussing the above stuff… 😐

Probably, I should give an example, what exactly I am going to represent here.

output

The above image specifies, one image in three different view-port. Here, the same image has been represented in 3 different sizes.

To get the above output – the developer/designer might have to write the following code –

<!DOCTYPE html>
<html>
    <head>
        <style>
            /* For wider screen */
            body {
                background: url('images/abc.jpg') no-repeat;
                background-size: 1400px auto;
            }
 
            /* For ipad */
            @media only screen and (min-width: 480px) and (max-width: 768px) {
                body {
                    background: url('images/abc.jpg') no-repeat;
                    background-size: 700px auto;
                }
            }
 
            /* For iphone */
            @media only screen and (max-width: 479px) {
                body {
                    background: url('images/abc.jpg') no-repeat;
                    background-size: 300px auto;
                }
            }
        </style>
    </head>
 
    <body></body>
</html>

OR

If we don’t want to load the same high resolution images in all the scenarios, then we can check with the below code –

<!DOCTYPE html>
<html>
    <head>
        <style>
            /* For wider screen */
            body {
                background: url('images/abc-high-res.jpg') no-repeat;
                background-size: 1400px auto;
            }
 
            /* For ipad */
            @media only screen and (min-width: 480px) and (max-width: 768px) {
                body {
                    background: url('images/abc-med-res.jpg') no-repeat;
                    background-size: 100% auto;
                }
            }
 
            /* For iphone */
            @media only screen and (max-width: 479px) {
                body {
                    background: url('images/abc-low-res.jpg') no-repeat;
                    background-size: 100% auto;
                }
            }
        </style>
    </head>
 
    <body></body>
</html>

We can customize more with the above code for best view in all the scenarios.

But, what is the use of picture element here ❓ 😕
.
.
.
.
No worries 😛 – lets put some light on the picture element now, the reason why we are reading this blog 😀

The output what we got from the above code, can be done easily, using picture element.

<!DOCTYPE html>
<html>
    <body>
        <picture>
            <source media="(max-width: 479px)" src="images/abc-low-res.jpg">
            <source media="(max-width: 768px)" src="images/abc-med-res.jpg">
            <source src="images/abc-high-res.jpg">
            <img src="images/abc-high-res.jpg" alt="This picture loads on non-supporting browsers.">
            <p>Accessible text.</p>
        </picture>
    </body>
</html>

That’s it :-). Isn’t it really interesting, that with the 4 lines of code only, we can achieve the above thing easily :-). Hmmm… sounds really interesting 🙂 :).

Note: Please check here for Browser support details.

Thanks 🙂 and will be happy to listen from you 🙂 :).