w3resource

JSONP Tutorial

Introduction to JSONP

In this page, we will discuss JSONP, i.e. JSON with padding. JSONP is used to request data from a server residing in a different domain. But why do we need a special technique to access data from a different domain? It's because of the Same Origin Policy.

Same Origin Policy

In general, this policy states that, if protocol (like http), Port number (like 80) and host (like example.com) is different from where data is being requested, it should not be permitted.

But HTML <script> element is allowed to perform content retrieval from foreign origins.

How JSONP works - Step by Step

Step 1 - You need to create a callback function. The function accepts some data. Like following code :

function w3r_callback(data){
         	  console.log(data);
         	  } 

Step 2 - Include a script in your web page which contains the callback function created a step 1 as a parameter.

<script src="http://www.example.com?q=w3r_callback"><script>

Step 3 - It outputs a script which calls the function and requested data is passed.

w3r_callback({
  "FirstName" : "xyz",
  "LastName"  : "abc",
  "Grade"     : "A"
         	  }
         	  );

Note

JSONP has nothing to do with Ajax, since it does not use XMLHttpRequest. Instead, it dynamically inserts <script> tag into a webpage.

But if you are using Jquery to do this sort of a job, you got to use Jquery's Ajax utility. Something like following -

 $.ajax({
         	  // ...
         	  dataType: 'jsonp',
         	  // ...
         	  }); 

Where to use JSONP

JSONP is mostly used to get data using RESTFull APIs(like Flicker).

Example - getting the latest updates from the flicker regarding tag "dogs" using Jquery and JSONP

<!DOCTYPE html>
  <html>
  <head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <title>An JSONP example from w3resource</title>
  </head>
  <body>
  <div id="images">
  </div>
  <script>
         	  $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
         	  {
         	  tags: "dogs",
         	  tagmode: "any",
         	  format: "json"
         	  },
         	  function(data) {
         	  $.each(data.items, function(i,item){
         	  $("<img/>").attr("src", item.media.m).appendTo("#images");
         	  if ( i == 3 ) return false;
         	  });
         	  });</script>
  </body>
  </html> 

View the output of above JSONP example in a separate browser window.

Previous: Introduction to BSON
Next: JSON Tutorial



Follow us on Facebook and Twitter for latest update.