What is JSONP, and why was it created?

Viewed 572221

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.

10 Answers

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.

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.

This is my 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 want to use on ourweb.com some JSON data (or any raw data really) 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

If only we could make 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 the 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)

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)
);

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);
Related