Check out my latest project: Full Frontal JavaScript Conference

What is JSONP?

jQuery 1.2 introduced JSONP support, but on initial read of the release notes, I wasn't completely sure what it was - so for anyone else that might want the Dr Seuss explanation.

JSONP is script tag injection, passing the response from the server in to a user specified function

How you can use JSONP

You need to mould both your request and response to handle JSONP - and in doing so, you can have cross domain JSON requests.

Your server will need to return the response as JSON, but also wrap the response in the requested call back, something like this in PHP (hosted on http://myotherserver.com):

$data = getDataAsJSON($_GET['id']);
echo $_GET['jsonp_callback'] . '(' . $data . ');';
// prints: jsonp123({"name" : "Remy", "id" : "10", "blog" : "http://remysharp.com"});

The jQuery script would be:

$.ajax({
  dataType: 'jsonp',
  data: 'id=10',
  jsonp: 'jsonp_callback',
  url: 'http://myotherserver.com/getdata',
  success: function () {
    // do stuff
  },
});

jQuery will change the url to include &jsonp_callback=jsonpmethod - but you can exclude it and it default to just 'callback'.

Example in the Wild

Twitter's JavaScript blog plugin works in exactly the same way. You create a function to handle the data from Twitter, and insert a script tag. Once the script is inserted, it calls the function passing the Twitter data as a JSON object.

How it works in jQuery

jQuery attaches a global function to the window object that is called when the script is injected, then the function is removed on completion.

Note that if the request is being made to the same domain, then jQuery will switch it down to a straight Ajax request.

Potential Problems

  1. Security. There's documents out on the web that can help, but as a cursory check, I would check the referrer in the server side script.
  2. There's no error handling. The script injection either works, or it doesn't. If there's an error from the injection, it'll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the server side.

25 Responses to “What is JSONP?”

  1. [...] What is JSONP?. Remy Sharp describes the JSONP method of script-tag injection and shows how it can be done with jQuery. [...]

  2. Good tip here on JSONP -- I'm going to look into it further.

    One thing: checking the referrer is basically useless from a security perspective, as it's provided by the client and very easy to forge.

  3. So one thing I'm noticing as a potential problem is the lack of support for the POST method. If I'm adding a comment or article via a webservice that provides JSONP support, I can't work outside the limitations of GET. Any thoughts on this?

  4. @Ryan - you're right, I can't think of a way to use a POST to get a JSONP response. If you're trying to write a REST API or something similar, you might want to send the POST, ignore the response, and use a GET JSONP to test for changes.

    Does that help?

  5. thx ramy, u help me out from the trouble.

    5 hours just to figure out this line:
    echo $_GET['jsonp_callback'] . '(' . $data . ');';

    :p

    tx u so much..

  6. I didn't know the server code had to be modified as well. Now I understand how JSONP works. Thanks

  7. [...] those interested, I've got a nice little trick inside the script which allows me to run a JSONP call and cancel it at a predefined [...]

  8. [...] XML, JSON, plain text, or JSONP (JSONP involves cross domain callbacks and is deconstructed with a PHP example here). The licensing agreement for the AideRSS API specifies only non-commercial [...]

  9. [...] packaged JSON data set uses JSONP for the callback pattern and thus to populate the page [...]

  10. [...] server-side proxy; dynamically creating a script tag), the beauty of Pipes is that it can return a JSONP response. By providing a callback function as an input argument, it is possible to perform [...]

  11. [...] Menu Tutorial 26. A Quick Code Igniter and JQuery Ajax Tutorial 27. jQuery and XML revisited 28. What is JSONP? 29. Creating A Sliding Image Puzzle Plug-In 30. Slide out and drawer effect 31. Creating accessible [...]

  12. [...] und knapp hat es Remy Sharp beschrieben, den ich seit einiger Zeit mit seiner aktuellen Version von Visualjquery ständig in meiner [...]

  13. I'm using JSONP and it works great. Thanks. Is this considered a 'hack' or 'legitimate'? You mention security. Are there problems for the site running the javascript, or just the server receiving the GET?

  14. Here's a C CGI that turns GET requests into POST requests with a target URL of your choosing - http://github.com/alandipert/jsonptunnel/tree/master

    This basically lets you POST to off-site URLs.

  15. [...] those of you unfamiliar with JsonP, it’s the process of using script injection to fetch data across domains (where Ajax requests prevent this access). You inject a script tag into your document with the url [...]

  16. [...] to be rhymed with (self-rhymes excluded), and the later wraps the results in a function callback in JSONP-style. Data is returned in JSON [...]

  17. Hello,

    very nice feature. But my server will need to return the response as JSON in Perl - not PHP.
    Can you help me, what would be the syntax for the Perl-Script?

    Thx for help,

    Rob

  18. [...] for leveraging existing #to_xml handlers where you already like them. Third, we’ve mixed in JSONP [...]

  19. [...] a JSONP call simply doesn't return back to the [...]

  20. Thanks for this Remy. I'd been looking all over the place trying to set up jsonp on my own server to transport data to one of my other sites. I was using jQuery's getJSON method on the client side but was not wrapping the function in the automatically created callback function on the server side. Finally clicked when I read through this post.

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight