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.

(function ($) {
    $.postJSON = function (url, obj, callback) {
            url: url,
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(obj),
            contentType: 'application/json; charset=utf-8',
            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.

Comments !