Sometimes when you do an ajax form post in jQuery, you need to merge another object into your post data. The idea behind this solution is to serialize the existing form data using jQuery’s $().serialize method. Then we use the $.param() utility method to create a serialized version of any javascript object or array. Simply concatenate the two and you are off to the races.

        var $form = $(form);

        var data = {
          'foo' : 'bar'
        };

        data = $form.serialize() + '&' + $.param(data);

        $.ajax({
          'type' : 'POST',
          'dataType' : 'json',
          'url' : $form.attr('action'),
          'data': data,

          'success': function(data) {
            //do something
          }
        });

Warning

A downside to this approach is the possibility of duplicated key names in your serialized string. Concatenating the two serialize strings won’t catch that. In that case you may be better off turning the form elements into an object and merging them using $.extend(). Check out this post on converting a query string into a javascript object.

Tagged with:
 
  • Ben

    Exactly what I was looking for! Thanks

  • Tix

    Using:

    data = $form.serialize() + “&foo=bar”;

    works fine as well

  • Than

    I used form.serialize() and the url length is more than the url`s limit as my form has lot of elements. Hence i could not process the url. this issue happens only in the form which has more elements. Is there a solution for this? Please suggest.

  • leniel

    JBLOTUS,

    One word:  Awesome.

    I was looking for this and it works as expected!

    Big thank you and keep posting interesting code pieces like this.

    All the best,

    Leniel

    • j_blotus

      Glad it helped! Cheers

  • Rawa

    Thanks! was taking too long to figure this out…