2434

I understand JSON, but not JSONP. Wikipedia's document on JSON is (was) the top search result for JSONP. It says this:

JSONP or "JSON with padding" is a JSON extension wherein a prefix is specified as an input argument of the call itself.

Huh? What call? That doesn't make any sense to me. JSON is a data format. There's no call.

The 2nd search result is from some guy named Remy, who writes this about JSONP:

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

I can sort of understand that, but it's still not making any sense.


So what is JSONP? Why was it created (what problem does it solve)? And why would I use it?


Addendum: I've just created a new page for JSONP on Wikipedia; it now has a clear and thorough description of JSONP, based on jvenema's answer.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Cheeso
  • 189,189
  • 101
  • 473
  • 713
  • 45
    For the record, do NOT use JSONP if you don't trust the server you're talking to 100%. If it is compromised, your webpage will be trivially compromised. – ninjagecko Jan 27 '12 at 20:56
  • 10
    Also note that JSONP [can be hijacked](http://security.stackexchange.com/a/84794/2379) if not implemented correctly. – Pacerier Mar 29 '15 at 07:20
  • 4
    I would like to give credit to the author of JSONP who gave the philosophy behind it: [Bob Ippolito's archive on JSONP](http://bob.ippoli.to/archives/2005/12/05/remote-json-jsonp/). He introduces JSONP as "a new technology agnostic standard methodology for the script tag method for cross-domain data fetching". – gawkface Feb 10 '17 at 06:05
  • 5
    For those who might arrive here more than a decade after the question through a search for something else and are confused: JSON-P is now also the name of a Java API for processing JSON, mainly parsing and writing it. It mirrors the XML StAX and DOM APIs, for streaming input/output and document modeling respectively. It supports JSON Pointer for querying, like XPath for XML. I think it also intends to provide the means to transform JSON through JSON Patch, like XML with XSLT and the Java XML Transformer API, but it's still a bit less advanced than XSLT. This question is about script injection. – G_H Sep 29 '21 at 21:18

10 Answers10

2282

It's actually not too complicated...

Say you're on domain example.com, and you want to make a request to domain example.net. To do so, you need to cross domain boundaries, a no-no in most of browserland.

The one item that bypasses this limitation is <script> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really do anything with the results, the script just gets evaluated.

Enter JSONP. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.

For example, say the server expects a parameter called callback to enable its JSONP capabilities. Then your request would look like:

http://www.example.net/sample.aspx?callback=mycallback

Without JSONP, this might return some basic JavaScript object, like so:

{ foo: 'bar' }

However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:

mycallback({ foo: 'bar' });

As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:

mycallback = function(data){
  alert(data.foo);
};

And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!

It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for JSONRequest is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.

These days (2015), CORS is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.

Rahul Gupta
  • 9,775
  • 7
  • 56
  • 69
Jerod Venema
  • 44,124
  • 5
  • 66
  • 109
  • 223
    Please note that using JSONP has some security implications. As JSONP is really javascript, it can do everything else javascript can do, so you need to trust the provider of the JSONP data. I've written som blog post about it here: http://erlend.oftedal.no/blog/?blogid=97 – Erlend Jan 14 '10 at 21:24
  • 79
    Is there really any new security implication in JSONP that is not present in a – Cheeso Jan 14 '10 at 21:45
  • 27
    Nope, it doesn't. It you trust it to deliver the javascript, same thing applies for JSONP. – Jerod Venema Jan 14 '10 at 21:52
  • 18
    It's worth noting that you can ramp up security a little by changing how the data is returned. If you return the script in true JSON format such as mycallback('{"foo":"bar"}') (note that the parameter is now a string), then you can parse the data manually yourself to "clean" it before evaluating. – Jerod Venema Jan 15 '10 at 00:04
  • 3
    @Cheeso: No it's the exact same problem. But some people fail to realize that this is a problem. @jvenema: You would still have to trust the provider of the data :-) – Erlend Jan 15 '10 at 10:13
  • 2
    @Erlend, no disagreement - any time you're loading something cross-domain, you'll have to have at least some trust in what you're loading :) – Jerod Venema Jan 17 '10 at 21:54
  • @jvenema CURL is also developed for cross domain data retrivation ( AFAIK) then what is the need of JSONP? – JustLearn Sep 08 '10 at 04:19
  • 10
    CURL is a server-side solution, not client-side. They serve two different purposes. – Jerod Venema Sep 08 '10 at 13:10
  • 3
    { foo: 'bar' } is completely legit as a JS object literal, which is what my example showed - JSONP works fine with object literals or strict JSON. – Jerod Venema Dec 09 '10 at 00:36
  • 7
    @Stephen `{ 'foo' : 'bar' }` is still not valid JSON. Double-quotes are required. – Joe Coder Mar 13 '13 at 00:41
  • 2
    @Cheeso - difference is – Martin Capodici Sep 24 '14 at 21:49
  • @Quentin - some good thoughts in your edit, but they change some of the simplicity and explicitness of the original answer. I've added an edit that references CORS as an option as well. – Jerod Venema Mar 03 '15 at 06:00
  • 1
    I think JSONRequest is a red herring, as far as I know there aren't any browsers that support it. – Quentin Mar 03 '15 at 07:51
  • It's also weird to give all the non-JSONP examples as fragments of JavaScript instead of JSON since people usually are using JSON already (especially if they are considering JSONP). – Quentin Mar 03 '15 at 07:55
  • Come to think of it, your example of JSONP isn't even JSONP. It's just JavaScript, but the function argument is invalid JSON. It'll work in most cases, but not for the occasional JSONP parser that strips off the callback stuff and then passes the rest to a JSON parser. – Quentin Mar 03 '15 at 08:18
  • 1
    it's worth pointing out that , returned script is __not__ allowed to mess with your DOM. That's why you pass your own function name which you have reference to. – Cholthi Paul Ttiopic Oct 06 '16 at 06:58
  • 3
    @CholthiPaulTtiopic — JSONP works by injecting a script into the page. The returned script can mess with the DOM as much as it likes. JSONP opens you up to XSS attacks from the data source, so you must trust the data source completely. (Which is why CORS is better, it doesn't suffer from this problem). – Quentin Jan 12 '17 at 15:32
  • 2
    I see the conventions of JSONP are designed around convenience rather than security – Cholthi Paul Ttiopic Jan 19 '17 at 09:21
  • 2
    It's a good explanation, very clear! 1. server using passed callback wrap the JSON data; 2. client using `script` bypassed Cross-Origin limit; 3. after script URL loaded, execute the global callback function – xgqfrms Aug 28 '19 at 06:33
794

JSONP is really a simple trick to overcome the XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTML tags, the ones you usually use to load js files, in order for js to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data';

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better(and it is):

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data?callback=my_callback';

Notice the my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain js array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.

NOTE: these are simple examples of JSONP usage, these are not production ready scripts.

Basic JavaScript example (simple Twitter feed using JSONP)

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>

Basic jQuery example (simple Twitter feed using JSONP)

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

erikvimz
  • 5,256
  • 6
  • 44
  • 60
ThatGuy
  • 14,941
  • 2
  • 29
  • 26
  • 41
    Thanks for the script tag explanation. I wasn't able to figure out how the cross domain security policy was bypassed by JSONP. After the explanation I feel a litte stupid to miss the point... – Eduard Aug 02 '12 at 07:35
  • 15
    This is a very good complementary answer to jvenema's answer - I didn't understand why the callback was necessary until you pointed out that the json data would otherwise have to be accessed via the script element. – Matt Mar 09 '14 at 01:26
  • 8
    Thanks for such lucid explanation. I wish my college textbooks were written by people like you :) – hashbrown Nov 21 '14 at 02:50
  • 1
    Good explication rather than the previous one. Ofcourse- your excerpt " the ones you usually use to load js files, in order for js to get data from another domain. Sounds weird?" is also eye opener for me. Example code in very much illustrious. – Learner Jul 24 '15 at 12:56
  • I like this explanation with concrete examples better than the accepted answer! Thanks! – ihor.eth Oct 23 '20 at 15:21
  • Why is this a not an accepted answer? The current accepted answer doesn't make sense, since it only mention ` – vanowm Aug 13 '21 at 14:56
60

This is a very ELI5 ("explain me like I'm 5") attempt for those that need it.

TL;DR

JSONP is an old trick invented to bypass the security restriction in web browsers that forbids us to get data that is in a different website/server (called different origin1) than our own.

The trick works by using a <script> tag to load a JSON (e.g.: { "city":"Barcelona" }) from somewhere else, that will send us the data wrapped in a function, the actual JSONP ("JSON with Padding"):

tourismJSONP({"city":"Barcelona"})

Receiving it in this way enables us to use the data within our tourismJSONP function. JSONP is a bad practice and not needed anymore, don't use it (read at the end).


The problem

Say we are building a new website, ourweb.com, and would love to show there some JSON data (or any raw data really) that's hosted at anotherweb.com. If we were to use GET request (think XMLHttpRequest, or fetch call, $.ajax, etc.), our browser would tell us it's not allowed with this ugly error:

Chrome CORS console error

This is a Content Security Policy restriction error, it's designed to protect users from certain attacks. You should just configure it properly (see at the end).

How would the JSONP trick help us here? Well, <script> tags are not subjected to this whole server (origin1) restriction! That's why we can load a library like jQuery or Google Maps from any server.

Here's the important point: if you think about it, those libraries are actual, runnable JS code (usually a massive function with all the logic inside). But raw data is not code. There's nothing to run; it's just plain text.

Hence, the browser will download the data pointed at by our <script> tag and when processing it'll rightfully complain:

wtf is this {"city":"Barcelona"} crap we loaded? It's not code. I can't compute!


The old JSONP hack

We're getting closer, we can pull the data but not manipulate/use it. If only we could make that plain text somehow runnable, we could grab it on runtime. We need anotherweb.com to send it as it if were code, so when it's downloaded on our visitor's browser will run it. We just need two things: 1) to get the data in a way that it can be run, and 2) write some code in the client so that when the data runs, our function is called and we get to use the data.

For 1) if the foreign server is JSONP friendly we'll ask for the data like this:

<script src="https://anotherweb.com/api/tourism-data.json?myCallback=tourismJSONP"></script>

So we'll receive it like this:

tourismJSONP({"city":"Barcelona"})

which now makes it JS code that we could interact with.

As per 2), we need to write a function with the same name in our code, like this:

function tourismJSONP(data){
  alert(data.city); // "Barcelona"
}

The browser will download the JSONP and run it, which calls our function, where the argument data will be the JSON data from anotherweb.com. We can now do with our data whatever we want to.


Don't use JSONP, use CORS

JSONP is a cross-site hack with a few downsides:

  • We can only perform GET requests
  • Since it's a GET request triggered by a simple script tag, we don't get helpful errors or progress info
  • There are also some security concerns, like running in your client JS code that could be changed to a malicious payload
  • It only solves the problem with JSON data, but Same-Origin security policy applies to other data (WebFonts, images/video drawn with drawImage()...)
  • It's not very elegant nor readable.

The takeaway is that there's no need to use it nowadays.

You should read about CORS here, but the gist of it is:

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.



  1. origin is defined by 3 things: protocol, port, and host. So, https://web.com is a different origin than http://web.com (different protocol), also https://web.com:8081 (different port) and obviously https://thatotherweb.net (different host)
Neithan Max
  • 11,004
  • 5
  • 40
  • 58
  • 9
    Hey man, this provided 100% clarity as a footnote to the approved answer! Thanks for this.... – M'Baku Jun 03 '20 at 02:11
  • 1
    JSONP is very useful for local development, because many browsers still implement CORS policies in a stringent way. E.g. Most browsers will allow your script make XMLHttpRequest to a CORS Domain, but you can't exchange cookie data unless you use a secure connection (HTTPS). Now, you can't use HTTPS for local development without an SSL certificate. Even if you generate a self signed SSL certificate, the browser still blocks it because it is not signed by a CA. Now to get it signed by a CA, your domain must be accessible on the internet so it can be verified. Pls pls... stop. JSONP is for me... – Udo E. Feb 07 '22 at 04:48
  • Just to add another disadvantage, JSONP requests that generate a unique callback function every time aren't cacheable because the query string is always different – Sean H Apr 07 '22 at 09:39
50

JSONP works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is tht JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.

For Further Reading Visit: https://blogs.sap.com/2013/07/15/secret-behind-jsonp/

client side snippet of code

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <title>AvLabz - CORS : The Secrets Behind JSONP </title>
     <meta charset="UTF-8" />
    </head>
    <body>
      <input type="text" id="username" placeholder="Enter Your Name"/>
      <button type="submit" onclick="sendRequest()"> Send Request to Server </button>
    <script>
    "use strict";
    //Construct the script tag at Runtime
    function requestServerCall(url) {
      var head = document.head;
      var script = document.createElement("script");

      script.setAttribute("src", url);
      head.appendChild(script);
      head.removeChild(script);
    }

    //Predefined callback function    
    function jsonpCallback(data) {
      alert(data.message); // Response data from the server
    }

    //Reference to the input field
    var username = document.getElementById("username");

    //Send Request to Server
    function sendRequest() {
      // Edit with your Web Service URL
      requestServerCall("http://localhost/PHP_Series/CORS/myService.php?callback=jsonpCallback&message="+username.value+"");
    }    

  </script>
   </body>
   </html>

Server side piece of PHP code

<?php
    header("Content-Type: application/javascript");
    $callback = $_GET["callback"];
    $message = $_GET["message"]." you got a response from server yipeee!!!";
    $jsonResponse = "{\"message\":\"" . $message . "\"}";
    echo $callback . "(" . $jsonResponse . ")";
?>
Liam Hammett
  • 1,631
  • 14
  • 18
Ajain Vivek
  • 1,111
  • 1
  • 12
  • 20
  • 3
    the link at the top just 404s now – Kevin Beal Mar 02 '14 at 23:52
  • The content of that link is now available at [http://scn.sap.com/community/developer-center/front-end/blog/2013/07/15/secret-behind-jsonp](http://scn.sap.com/community/developer-center/front-end/blog/2013/07/15/secret-behind-jsonp). – ᴠɪɴᴄᴇɴᴛ Aug 26 '14 at 14:19
43

Because you can ask the server to prepend a prefix to the returned JSON object. E.g

function_prefix(json_object);

in order for the browser to eval "inline" the JSON string as an expression. This trick makes it possible for the server to "inject" javascript code directly in the Client browser and this with bypassing the "same origin" restrictions.

In other words, you can achieve cross-domain data exchange.


Normally, XMLHttpRequest doesn't permit cross-domain data-exchange directly (one needs to go through a server in the same domain) whereas:

<script src="some_other_domain/some_data.js&prefix=function_prefix>` one can access data from a domain different than from the origin.


Also worth noting: even though the server should be considered as "trusted" before attempting that sort of "trick", the side-effects of possible change in object format etc. can be contained. If a function_prefix (i.e. a proper js function) is used to receive the JSON object, the said function can perform checks before accepting/further processing the returned data.

hlev
  • 551
  • 1
  • 7
  • 20
jldupont
  • 93,734
  • 56
  • 203
  • 318
  • 2
    "append a prefix" is confusing :) – jub0bs Jan 22 '20 at 08:06
  • Not sure the caveat about containing fallout is accurate. A malicious server could return `function_prefix();super_dangerous_function{window.open('youvebeenhacked!')}()` – apod Apr 07 '21 at 03:18
18

JSONP is a great away to get around cross-domain scripting errors. You can consume a JSONP service purely with JS without having to implement a AJAX proxy on the server side.

You can use the b1t.co service to see how it works. This is a free JSONP service that alllows you to minify your URLs. Here is the url to use for the service:

http://b1t.co/Site/api/External/MakeUrlWithGet?callback=[resultsCallBack]&url=[escapedUrlToMinify]

For example the call, http://b1t.co/Site/api/External/MakeUrlWithGet?callback=whateverJavascriptName&url=google.com

would return

whateverJavascriptName({"success":true,"url":"http://google.com","shortUrl":"http://b1t.co/54"});

And thus when that get's loaded in your js as a src, it will automatically run whateverJavascriptName which you should implement as your callback function:

function minifyResultsCallBack(data)
{
    document.getElementById("results").innerHTML = JSON.stringify(data);
}

To actually make the JSONP call, you can do it about several ways (including using jQuery) but here is a pure JS example:

function minify(urlToMinify)
{
   url = escape(urlToMinify);
   var s = document.createElement('script');
   s.id = 'dynScript';
   s.type='text/javascript';
   s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
   document.getElementsByTagName('head')[0].appendChild(s);
}

A step by step example and a jsonp web service to practice on is available at: this post

dardawk
  • 456
  • 4
  • 8
  • 3
    Thanks for posting your answer! Please note that you should post the essential parts of the answer here, on this site, or your post risks being deleted [See the FAQ where it mentions answers that are 'barely more than a link'.](http://stackoverflow.com/faq#deletion) You may still include the link if you wish, but only as a 'reference'. The answer should stand on its own without needing the link. – Taryn Mar 28 '13 at 19:24
14

A simple example for the usage of JSONP.

client.html

    <html>
    <head>
    </head>
    <body>

    <input type="button" id="001" onclick=gO("getCompany") value="Company"  />
    <input type="button" id="002" onclick=gO("getPosition") value="Position"/>
    <h3>
      <div id="101">
    
      </div>
    </h3>

    <script type="text/javascript">

    var elem=document.getElementById("101");

    function gO(callback){

    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://localhost/test/server.php?callback='+callback;
    elem.appendChild(script);
    elem.removeChild(script);    
    }

    function getCompany(data){

    var message="The company you work for is "+data.company +"<img src='"+data.image+"'/   >";
    elem.innerHTML=message;
    }

    function getPosition(data){
    var message="The position you are offered is "+data.position;
    elem.innerHTML=message;
    }
    </script>
    </body>
    </html>

server.php

  <?php

    $callback=$_GET["callback"];
    echo $callback;

    if($callback=='getCompany')
    $response="({\"company\":\"Google\",\"image\":\"xyz.jpg\"})";
 
    else
    $response="({\"position\":\"Development Intern\"})";
    echo $response;

    ?>    
Lemon
  • 3
  • 4
sarath joseph
  • 2,533
  • 2
  • 20
  • 23
7

Before understanding JSONP, you need to know JSON format and XML. Currently the most frequently used data format on the web is XML, but XML is very complicated. It makes users inconvenient to process embedded in Web pages.

To make JavaScript can easily exchange data, even as the data processing program, we use the wording according to JavaScript objects and developed a simple data exchange format, which is JSON. JSON can be used as data, or as a JavaScript program.

JSON can be directly embedded in JavaScript, using them you can directly execute certain JSON program, but due to security constraints, the browser Sandbox mechanism disables cross-domain JSON code execution.

To make JSON can be passed after the execution, we developed a JSONP. JSONP bypass the security limits of the browser with JavaScript Callback functionality and the < script > tag.

So in short it explains what JSONP is, what problem it solves (when to use it).

Marcus Thornton
  • 5,955
  • 7
  • 48
  • 50
  • 5
    I downvoted this because I don't believe the statement that XML was the most used dat format on the web in Dec '15. – RobbyD Jan 16 '17 at 15:55
  • 2
    It still doesn't asnwer why jsonp is used instead of json. Where are all those security restrictions coming from? Why can we use jsonp but not json for cross-domains? – Merunas Grincalaitis Feb 10 '20 at 08:07
1

JSONP stands for JSON with Padding.

Here is the site, with great examples, with the explanation from the simplest use of this technique to the most advanced in plane JavaScript:

w3schools.com / JSONP

One of my more favorite techniques described above is Dynamic JSON Result, which allow to send JSON to the PHP file in URL parameter, and let the PHP file also return a JSON object based on the information it gets.

Tools like jQuery also have facilities to use JSONP:

jQuery.ajax({
  url: "https://data.acgov.org/resource/k9se-aps6.json?city=Berkeley",
  jsonp: "callbackName",
  dataType: "jsonp"
}).done(
  response => console.log(response)
);
simhumileco
  • 31,877
  • 16
  • 137
  • 115
0

Background

You should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.

Examples

JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)

JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest and the associated browser methods. Instead, a <script> tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head> element).

JSON Request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // success
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP Request:

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';
  
document.getElementsByTagName("head")[0].appendChild(tag);

The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.

JSON:

 { "bar": "baz" }

JSONP:

foo( { "bar": "baz" } );

This is why you see JSONP requests containing the callback parameter so that the server knows the name of the function to wrap the response.

This function must exist in the global scope at the time the <script> tag is evaluated by the browser (once the request has been completed).

Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.

Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.

Using jQuery

The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.

By default, jQuery requires you to include &callback=? in the URL of your AJAX request. jQuery will take the success function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ? in &callback=? with the name it has assigned.

Comparing similar JSON and JSONP Implementations

The following assumes a response object { "bar" : "baz" }

JSON:

   var xhr = new XMLHttpRequest();
    
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4 && xhr.status == 200) {
        document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
      };
    };
    
    xhr.open("GET", "somewhere.php", true);
    xhr.send();

JSONP:

 function foo(response) {
      document.getElementById("output").innerHTML = response.bar;
    };
    
    var tag = document.createElement("script");
    tag.src = 'somewhere_else.php?callback=foo';
    
    document.getElementsByTagName("head")[0].appendChild(tag);
samnoon
  • 1,340
  • 2
  • 13
  • 23