jQuery: serialize a form as a JSON object

If you're using AJAX with a form and you want to pass a JSON object to one of the jQuery's AJAX methods used to process the request, you will probably wonder how this could be done. Basically, you should convert your form values to a plain array, loop through all the items in the array and finally return a plain object literal. Let's see the details.

We can put all the aforementioned routines in a simple jQuery plugin:

(function($) {
$.fn.serializeFormJSON = 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;
};
})(jQuery);

We start with an empty object literal which will be populated by looping through the array returned by the serializeArray() function. Here's a use case:

$('#contact').submit(function(e) {

 var $form = $(this);
 var data = $form.serializeFormJSON();
 
 $.post('process.php', data, function(output) {
 
  // do something here
 
 });

 e.preventDefault();

});

2 thoughts on “jQuery: serialize a form as a JSON object”

  1. Thanks for the plugin, very helpful. However, I think there's a small bug in Line 7. It should be:
    if (o[this.name] !== undefined) {

    Otherwise, if there are multiple values and the first one is "falsy", it will be overwritten.

Leave a Reply

Note: Only a member of this blog may post a comment.