What Is Jsonp, and Why Was It Created

What is JSONP, and why was it created?

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.

Can anyone explain what JSONP is, in layman terms?

Preface:

This answer is over six years old. While the concepts and application of JSONP haven't changed
(i.e. the details of the answer are still valid), 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.


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 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.


Comparable JSON/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);

What are the differences between JSON and JSONP?

JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:

//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json){
alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

Confused on how a JSONP request works

The callback is a function YOU'VE defined in your own code. The jsonp server will wrap its response with a function call named the same as your specified callback function.

What happens it this:

1) Your code creates the JSONP request, which results in a new <script> block that looks like this:

<script src="http://server2.example.com/RetrieveUser?UserId=1234&jsonp=parseResponse"></script>

2) That new script tag is executed by your browser, resulting in a request to the JSONP server. It responds with

parseResponse({"Name": "Foo", "Id" : 1234, "Rank": 7});

3) Since this request came from a script tag, it's pretty much EXACTLY the same as if you'd literally placed

<script>
parseResponse({"Name": "Foo", "Id" : 1234, "Rank": 7});
</script>

into your page.

4) Now that this new script has been loaded from the remote server, it will now be executed, and the only thing it will do is a function call, parseResponse(), passing in the JSON data as the function call's only parameter.

So somewhere else in your code, you'd have:

function parseResponse(data) {
alert(data.Name); // outputs 'Foo'
}

Basically, JSONP is a way of bypassing the browser's same-origin script security policy, by having a 3rd party server inject a function call directly into your page. Note that this is by design highly insecure. You're depending that the remote service is honorable and doesn't have malicious intent. Nothing stops a bad service from returning some JS code that steals your banking/facebook/whatever credentials. e.g.... the JSONP response could've been

 internalUseOnlyFunction('deleteHarddrive');

rather than parseReponse(...). If the remote site knows the structure of your code, it can perform arbitrary operations with that code, because you've opened your front door wide-open to allow that site to do anything it wants.

Explanation and usage of JSONP

JSONP stands for JSON with padding, and it provides a way for the client to specify some code that should be added to the start of the JSON response. This allows the JSONP response to be directly executed in the browser. An example of a JSONP response might be:

processResults({value1: "Hello", value2: "World"})

I think the major place that JSONP would be useful is in making requests across domains using the <script> tag. I think the major disadvantage is that as the JSONP is directly executed you would have to trust that the remote site wouldn't send back anything malicious. However I have to admit that I haven't used the technique in practice.

Edit: Remote JSON - JSONP provides more information on why you would want to use the technique from the guy who appears to have invented it.

What Is Difference Between Json and Jsonp?

JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.

But the practical implementation of the approach involves subtle differences that are often not explained clearly.

Here is a simple tutorial that shows JSON and JSONP side by side.

All the code is freely available at Github and a live version can be found at http://json-jsonp-tutorial.craic.com

Difference between dataType jsonp and JSON

dataType: jsonp for cross-domain request, that means request to different domain and dataType: json for same domain-same origin request.

Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the
end of your URL to specify the callback. Disables caching by appending
a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache
option is set to true.

Read about same origin policy

Read more about jQuery AJAX

What does the 'P' in JSONP stand for?

Padding.

from http://en.wikipedia.org/wiki/JSONP

JSONP or "JSON with padding" is a complement to the base JSON data
format, a pattern of usage allowing a page to request data from a
server in a different domain. JSONP is a solution to this problem,
forming an alternative to a more recent method called Cross-Origin
Resource Sharing.
Padding

While the padding (prefix) is typically the name of a callback
function that is defined within the execution context of the browser,
it may also be a variable assignment, an if statement, or any other
Javascript statement. The response to a JSONP request (namely, a
request following the JSONP usage pattern) is not JSON and is not
parsed as JSON; the returned payload can be any arbitrary JavaScript
expression, and it does not need to include any JSON at all. But
conventionally, it is a Javascript fragment that invokes a function
call on some JSON-formatted data.

Said differently, the typical use of JSONP provides cross-domain
access to an existing JSON API, by wrapping a JSON payload in a
function call.

Hope that helped. Google wins!

How do I set up JSONP?

Assuming your server is running PHP, you just need to add 'callback' GET request.

<?php header('content-type: application/json; charset=utf-8');
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['callback'] . '('.json_encode($data).')';

And on client side (using jQuery):

$.ajax({url: 'http://site.com/data.php', dataType:'jsonp'});

The PHP code above is just for demo, don't forget to sanitise $_GET['callback']

That said, if your issue just the same origin policy, you'll probably just need to allow cross-origin from the server side, and everything should work.



Related Topics



Leave a reply



Submit