Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set up JSONP?

What do I need to on the server side to allow someone to get data from that server using JSONP. And what do I need to do on the user side as well? I want to use JSONP as an alternative to an XMLHttpRequest.

It won't work out of my Firefox extension, because of the same-origin policy. So, people recommended JSON, but I am pretty lost after searching for tutorials and guides on the internet.

Thanks for the help!

like image 690
Jacques Blom Avatar asked Mar 01 '12 15:03

Jacques Blom


People also ask

How do I create JSONP?

It's idea is to simply return a JavaScript file which calls the callback function with the JSON object as the first parameter of the JavaScript callback function. You can use the built-in json_encode() function to create JSON strings (which $data in our example above contains) from arrays and objects in PHP.

How do I use JSONP?

Method to use JSONP: In the URL include the callback parameter in the end. When the browser comes across the script element, it sends HTTP request to the source URL. The server sends back the response with JSON wrapped in a function call.

How does JSONP request work?

Standard JSON Asynchronous request The browser makes an asynchronous POST request to the server slapping its parameters to the service in the body. The server responds with a string of JSON data. A success handler of the request fires and the string is converted into a Javascript Object to be used in the application.

Why should we avoid JSONP?

JSONP has some other limitations, too: It can only be used for GET requests, and there's no general way to prevent cross-site request forgeries*. It's bad for private data, since any site on the web could hijack a JSONP response if the URL is known. This means it's best suited for consumption of public data feeds.


3 Answers

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.

like image 139
marko Avatar answered Oct 04 '22 15:10

marko


On the server side, all you have to set up is a web resource (e.g., page) that accepts a GET request and returns the data using the JSON-P convention, which is:

callback({"data": "here"});

...where the function name ("callback" in that example) is usually taken from one of the query string parameters (by convention, the parameter "callback"), and the data is JSON text (although technically it could be anything that's valid in a JavaScript object literaly, the convention with JSON-P is to restrict yourself to what's valid in JSON). So for instance, let's say that the request looked like this:

http://example.com/foo.php?callback=bar

That calls the page foo.php (doesn't have to be PHP, can be any dynamic server-side system), telling it that the function we want it to call is "bar". Our response would be:

bar({"data": "here"});

On the client side, you have to add a script element to the page dynamically, and also add the callback function that will get triggered by the JSON-P response. Usually you want to give that function some random name, and remove it when you're done.

Here's a complete example as an answer to another question here on Stack Overflow. You may have to adapt it slightly for use in a Firefox add-on, but the concepts are the same.

like image 38
T.J. Crowder Avatar answered Oct 04 '22 17:10

T.J. Crowder


jsonp is json with a wrapper, so you can fake ajax requests to another server by dynamically inserting new <script> tags, with src's pointing at the other server. The wrapper essentially makes the jsonp return stuff be a valid javascript function call that can be executed to extract the standard json data within.

Generally, in an insecure 'just to demo' version, you'd have something like this:

function unwrap_jsonp(data) {
    eval(data);
}

The remote server would return the following literal text:

unwrap_json("{'this':'is','sparta':'!'}");

Note that this is literal Javascript plaintext code, which is executed and "unwraps" the embedded JSON string back to a native javascript data structure.

Most JSONP services allow specifying an extra parameter via the query string to name the handler function you want to wrap the response in, e.g.

http://example.com/getjsonp.php?callback=unwrap_json
like image 41
Marc B Avatar answered Oct 04 '22 15:10

Marc B