Combine serialized form ajax post data with an arbitrary object using jQuery post

Comments

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.

<html>
<script>
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
  }
});
</script>
</html>

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.

  • Tags:
  • $.extend
  • $.param
  • ajax
  • javascript
  • jquery
  • serialize

explosive web programming MODERN CODE TACTICS

by James Fuller