Thursday, November 10, 2011

jQuery's Ajax POST Parameters

Most of the AJAX requests on our site utilize jQuery's $.post() method, building up a datastring of key/value pairs and sending that string right on through. Because of this, I had to manually replace all & characters with their URL equivalent, %26. But in one case, I discovered that the % was being converted to %25, resulting in a string of %2526...not at all what I wanted.

It turns out that it matters whether you send a datastring or a map. This is taken from jQuery's API referencing the $.ajax() method:


The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false.

Unfortunately, it does not seem possible to set processData from $.post(), which is simply a wrapper for $.ajax(). So, to be consistent, all of our AJAX requests should either utilize maps (thereby automatically escaping URL values), or the individual variables will have to be escaped manually. The first option seems to be a lot cleaner, but most of our requests use the latter form. What to do, what to do...