JavaScript: same origin policy and JSONP

luca 11/07/2013 2

The same origin policy is a security policy that all the modern browsers apply to client-side scripting languages, including JavaScript. That policy prevents a script running in the browser from calling methods and resources offered by different websites from the one that hosts the script

For example if a script, hosted on, tries to make an AJAX request (using XmlHttpRequest) to, the request is blocked:

Sometimes you need to bypass this restriction: for example think about a website that – using JavaScript – has to retrieve tweets from Twitter… the solution is called JSONP!


JSONP (JSON with padding) is a communication technique that extends JSON data-exchange format.

This technique take advantage of the lazy loading, that is the ability to add – at runtime – new scripts to an HTML page. This method is not restricted by the same origin policy.

A normal JSON response contains data, for example:

  title: “La Divina Commedia”,
  author: “Dante Alighieri”

With JSONP instead, data is passed as argument of a callback function:

  title: “La Divina Commedia”,
  author: “Dante Alighieri”

The response to a JSONP request is therefore a JavaScript code, that is run by the browser.

Dynamic callback

In the previous example, the callback funcion’s name is static; with a change in the server-side method that creates the JSONP response, you can make it dynamic, able to respond to any JSONP request.

The trick is to pass, as a request’s parameter, the name of the function:

the server-side script will create the JSONP response using that parameter… for example in PHP:

$data = array('title' =--> 'La Divina Commedia', 'author' => 'Dante Alighieri');
$json = json_encode($data); 
$jsonp_callback = isset($_GET['callback']) ? $_GET['callback'] : null;	
print $jsonp_callback ? "$jsonp_callback($json)" : $json;


jQuery makes easy the use of JSONP: you need only to add callback=? to the URL in the getJSON method and jQuery will generate a callback function for you:

If the URL includes the string “callback=?” (or similar, as defined by the server-side API), the request is treated as JSONP instead

With the more general ajax method you can instead change all the request’s settings, including the name of the function.


  1. Mauro 23/04/2014 at 06:35 - Reply

    É sempre piacevole cercare un argomento sul web e scoprire che tu lo hai già trattato in maniera ineccepibile e chiara :-)

    Grande Luca

Leave A Response »

This website uses cookies to ensure you get the best experience on our website maggiori informazioni

Questo sito utilizza i cookie per fonire la migliore esperienza di navigazione possibile. Continuando a utilizzare questo sito senza modificare le impostazioni dei cookie o clicchi su "Accetta" permetti al loro utilizzo.