How do I set up JSONP?

Jacques Blom picture Jacques Blom · Mar 1, 2012 · Viewed 14.8k times · Source

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!

Answer

marko picture marko · Mar 1, 2012

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.