jQuery: getting form data for Ajax

One of the most requested features when using Ajax with jQuery is something that can be used to prepare a serialized string to be passed to the $.ajax() method. Many plugins that deal with forms provide this feature, though not all of these plugins serialize data in the same way. So I've created the following jQuery plugin that serializes form data and turns it into a string:

(function($)) {

    $.fn.getFormData = function() {
   
       var data = [];
       
       this.find(':input').not(':submit').each(function() {
 
         var $inputName = $(this).attr('name');
         var $inputVal = $(this).val();
         var formValue = $inputName + '=' + $inputVal;
         data.push(formValue);
     
         
      });
     
     
      return data.join('&');
   
   
   
   };

})(jQuery);

Example:

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

    var data = $(this).getFormData();
    
    $.ajax({
    
        type: 'POST',
        url: 'ajax.php',
        data: data,
        success: function(html) {
        
            alert(html);
        
        }
    
    });
    
    e.preventDefault();

});

The getFormData() method collects all the values of the input and textarea elements, but it doesn't take into account the submit button of a form. It can be used in a variety of contexts and it's really lightweight.

Leave a Reply

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