Click here to Skip to main content
15,881,173 members
Articles / Programming Languages / Javascript

Handy Tips to Handle Form Submit using AJAX

Rate me:
Please Sign up or sign in to vote.
3.97/5 (12 votes)
21 Jul 2015CPOL2 min read 11.2K   10   8
Here are some handy tips to handle form submit using Ajax

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.

  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. Let's put some light in there. :).

Tip – 1

Get all form data individually and put in key=>value format like below:

JavaScript
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:

JavaScript
$("#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.

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

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

JavaScript
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.

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

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

JavaScript
$.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.:

JavaScript
formData.first_name ==> Rasmus

Tip – 4

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

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

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

JavaScript
$.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.

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Software engineer with around 6 years of web application development experience in open source technologies like PHP, MySQL, HTML, HTML5, CSS, CSS3, Javascript, jQuery etc.

I love to learn and share my knowledge in which manner I can and like to solve the issues as in the coding perspective. I am an active contributor in community forums like StackOverflow, CodeProject etc. Besides that, I write blogs in free time and speak in various technical community events.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Suvendu Shekhar Giri6-Aug-15 0:18
professionalSuvendu Shekhar Giri6-Aug-15 0:18 
Nice article !
GeneralRe: My vote of 5 Pin
Prava-MFS6-Aug-15 0:27
professionalPrava-MFS6-Aug-15 0:27 
QuestionVote 5 Pin
zpaulo_carraca23-Jul-15 7:08
zpaulo_carraca23-Jul-15 7:08 
AnswerRe: Vote 5 Pin
Prava-MFS23-Jul-15 15:34
professionalPrava-MFS23-Jul-15 15:34 
GeneralMy vote Pin
Member 1135189322-Jul-15 20:11
Member 1135189322-Jul-15 20:11 
AnswerRe: My vote Pin
Prava-MFS23-Jul-15 15:32
professionalPrava-MFS23-Jul-15 15:32 
GeneralMy vote of 4 Pin
hoangcute9x21-Jul-15 18:35
professionalhoangcute9x21-Jul-15 18:35 
AnswerRe: My vote of 4 Pin
Prava-MFS21-Jul-15 19:38
professionalPrava-MFS21-Jul-15 19:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.