$.postJSON() for jQuery

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

$.getJSON() is pretty handy for sending an AJAX request and getting back JSON data as a response. Alas, the jQuery documentation lacks a sister function that should be named $.postJSON(). Why not just use $.getJSON() and be done with it? Well, perhaps you want to send a large amount of data or, in my case, IE7 just doesn’t want to work properly with a GET request.

It is true, there is currently no $.postJSON() method, but you can accomplish the same thing by specifying a fourth parameter (type) in the $.post() function:

// Send the request
$.post('script.php', data, function(response) {
    // Do something with the request
}, 'json');

This works for $.get() as well, which means $.getJSON() is basically a call to $.get() with ‘json’ as the fourth parameter.

If you enjoyed this article, please share it with a friend!

2 Responses to $.postJSON() for jQuery

  1. I created a different version of this code that parses the response string, it’s on my website. Normally the response is a string not an object.

  2. Madbreaks says:

    Interesting, I’ll give it a try. It was IE7′s refusal to submit my call to getJSON that initially brought me here. I’ve done more testing and determined that it always works as long as:

    1. The ‘data’ argument isn’t too long. Somewhere around 2048 is the limit for IE get requests, including the base URL.

    2. I call $.ajaxSetup({ cache: false }); before I send the getJSON request.

    All well and good unless you have a lot of data to send, which I do. So I’m going to give your approach a try, thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>