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 🙂 :).