What are the differences between json and jsonp ?

JSON (Javascript Object Notation) is a convenient way to transport data between applications, especially when the destination is a Javascript application.

JSON format looks like:

{
     "Name": "Tony Stark",
     "Job": "Milionaire",
     "Nickname": "Iron man",
     "Team": "The Avenger"
}

The easiest way to load json data into web application is using the ajax() method which is available in jQuery library. It looks like:

$.ajax(
     type:'GET',
     url:"getJSON.php",
     data:"format=json&id=123",
     success:function(feed) {
          document.write(feed);
     },
);

How about the JSONP?

JSONP (JSON with padding) is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy.

Basically, we use JSONP when we want to request data from another server. For example, we build a web application and we need to get the data from facebook api like how many comments on your web pages, who comment, … This time, we need to use the JSONP to sent request to facebook api.

Mr Web Developer says “I’ve tried every way I could think of to load scripts from external domains. It’s just not possible unless you have access to the server side scripts or have a proxy pass in place between the domains. BUT, what we do have is jQuery’s JSONP provides us with an reluctantly acceptable workaround.”

The most common error that you will see when using JSON instead of JSONP is Access-Control-Allow-Origin.

So, what does JSONP looks like ? The difference between a JSON response and a JSONP response, is that the JSONP response is formulated such that the response object is passed as an argument to a callback function.

Superhero({
     "Name": "Tony Stark",
     "Job": "Milionaire",
     "Nickname": "Iron man",
     "Team": "The Avenger"
)}

For this example, all of the data now are wrap inside a callback function name “Superhero”.

Once again, to load the JSONP data we  continue using ajax() method

$.ajax({
     url : "http://192.168.1.12:8080/users",
     async: true,
     dataType: "jsonp",
     success : function(res) {
          $.each(res, function(key, value) {
               $('#test').append('<h1>User ' + value.name + '</h1>');
          });
     },
     error: function(){
          alert('error!');
     }
});

It’s almost the same with the way to load JSON. All we need is change the dataType to JSONP