Peter Stuifzand

jQuery and postJSON

The last few days I’ve been using jQuery to write some REST based javascript and HTML. While I was doing that I needed a function that looked like getJSON, that did a POST instead of a GET. The difference is that I send a bit of JSON and receive a bit of JSON, instead of sending form-like data. So I created the following bit of code:

$.postJSON = function (url, data, callback) {
    $.ajax({
        'url': url,
        'type': 'post',
        'processData': false,
        'data': JSON.stringify(data),
        contentType: 'application/json',
        success: callback,
    });
};

If you know jQuery a bit, you will know that this sends an Ajax request to url. Later when I used this code to do a POST a followed by a GET, I didn’t receive the thing that I wanted: a Javascript object. I did however get a string that looked like one. That confused me for a bit. Then I remembered a FAQ or a weblog post about another implementation of postJSON, that was written like this.

$.postJSON = function(url, data, callback) {
    jQuery.post( url, data, callback, "json") ;
};

It seemed my problems where solved. When I clicked around my website, everything had stopped working. I checked what this code was doing and it did something different than what I expected. It doesn’t send the data variable as JSON, but as application/x-form-encoded.

First the problem was that the code didn’t parse the return value. Then the problem became that the code didn’t encode the arguments as JSON. When I found the problem the change was easy: change the callback to parse the return value. The final code became this:

$.postJSON = function (url, data, callback) {
    $.ajax({
        'url': url,
        'type': 'post',
        'processData': false,
        'data': JSON.stringify(data),
        contentType: 'application/json',
        success: function (data) { callback(JSON.parse(data)); },
    });
};

The current problem is that this method has a different interface than the normal postJSON. So I have to choose a different name.

© 2023 Peter Stuifzand