Posting an AJAX JSON request with jQuery

After trying to Google this for the fifth time, and writing it from scratch for the seventh time, I’m sticking this snippet here. In AJAX apps, it’s always made sense to me to do JSON both ways, even though the jQuery default is form-data up and whatever down. Once ASP.NET MVC3 made JSON model binding turned on by default, something like the below is a natural next step.

(<span class="kwrd">function</span> ($) {
    $.postJSON = <span class="kwrd">function</span> (url, obj, callback) {
        $.ajax({
            url: url,
            type: <span class="str">'POST'</span>,
            dataType: <span class="str">'json'</span>,
            data: JSON.stringify(obj),
            contentType: <span class="str">'application/json; charset=utf-8'</span>,
            success: callback
        });
    };
} (jQuery));

Note: JSON.stringify is built in to modern browsers now, but for older browser just find json2.js (commonly available) and include it on your page.

This entry was posted in CodeMinder, JavaScript, JSON, Programming, REST. Bookmark the permalink.
  • sas

    kll