Using jquery to make a POST, how to properly supply ‘data’ parameter?

An easier way is to provide the data property as an object, like this:

$.ajax({
  url: 'mysite/save',
  type: 'POST',
  data: { param0:'hi there!', param1:'blah blah', param2:'we get it' }
});

Otherwise, yes you should encode it, as anything with an & for example would screw things up very quickly. Providing it as an object represents a much clearer/simpler approach though, in my opinion anyway.

You can also space it out and retrieve properties from other places inline, like this:

$.ajax({
  url: 'mysite/save',
  type: 'POST',
  data: { 
          param0: $('#textbox0').val(), 
          param1: $('#textbox1').val(), 
          param2: $('#textbox2').val()
        }
});

Edit: If you’re curious how jQuery does this encoding internally, it’s using $.param() (which you can use directly as well) to encode the object to a string, called here, and the guts here.

Leave a Comment