In this post, I am going to explain different ways to handle form submit using AJAX.
Basically, to submit a form via AJAX, we need to follow a certain process in our JavaScript file.
- Process form submit event
- Get all the form data using JavaScript/jQuery
- Submit the form with data using AJAX
- 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. Let's put some light in 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 ways 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 I will be happy to hear from you :) :).
CodeProject