What is JSONP and how to use it in jQuery & JavaScript

What is JSONP and how to use it in jQuery & JavaScript

JSONP stands for JSON with padding. The padding refers the function call that wraps the JSON object.

What is JSONP – JSON vs JSONP

JSONP is JSON with a function call that wraps the JSON. See below:

JSON:

{
  "id": 1,
  "room": "main bedroom",
  "items": [ "bed", "chest of drawers" ]
}

JSONP:

jsonpcallback({
  "id": 1,
  "room": "main bedroom",
  "items": [ "bed", "chest of drawers" ]
});

The above 2 codes just has one difference which is the function call jsonpcallback() that is wrapping the JSON.

What is the use of JSONP

JSONP is used to bypass the Cross-Domain Request boundaries, under which the scripts that run on one domain are restricted to access the data from another page on different domain.

This is also known as Same-origin policy of the web browsers.

To explain this further, due to this Same-origin policy I cannot fetch JSON file which is located under somedomain.com, by running jQuery AJAX method on my domain yogihosting.com.

jQuery JSONP Example

Let see how to work with JSONP in jQuery.

In this Example I have a JSON file that is located on the URL – http://www.demo.yogihosting.com/jquery/jsonp/data.json

This JSON file looks like:

{
  "id": 1,
  "room": "main bedroom",
  "items": [ "bed", "chest of drawers" ]
}	

Next with jQuery AJAX method I try to fetch this file – from my local PC.

$.ajax({
    url: "http://www.demo.yogihosting.com/jquery/jsonp/data.json",
    dataType: "json",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function (result, status, xhr) {
        alert(result);
    },
    error: function (xhr, status, error) {
        alert("Error")
    }
}); 

On my console window I get error stating –

Failed to load http://www.demo.yogihosting.com/jquery/jsonp/data.json: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:32617’ is therefore not allowed access.

no access control allow origin

Solving No ‘Access-Control-Allow-Origin’ problem

I create a new JSON file but this time wrap it with a function call. This JSONP file location is: http://www.demo.yogihosting.com/jquery/jsonp/data1.json

Its contents remain the same.

processJSONPResponse( {
  "id":  1,
  "room": "main bedroom",
  "items": [ "bed", "chest of drawers" ]
})

The wrapped function is processJSONPResponse().

Next, update the jQuery AJAX code to put dataType: “jsonp” and jsoncallback property like this:

$.ajax({
    url: "http://www.demo.yogihosting.com/jquery/jsonp/data1.json",
    dataType: "jsonp", // jsonp
    type: "POST",
    jsonpCallback: 'processJSONPResponse', // add this property
    contentType: "application/json; charset=utf-8",
    success: function (result, status, xhr) {
        console.log(result);
    },
    error: function (xhr, status, error) {
        console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
    }
});

In this way, now I can easily fetch a JSON file from another domain using the JSONP method.

Do you love animations and like to create a few of them in your site? Then check the jQuery Animate method that helps you to create a few of them within a few minutes.

Fetch JSONP using JavaScript

You can also fetch the JSONP contents using JavaScript. Here there are 3 main steps:

  • 1.Create a script tag and give its src value to the JSONP file location.
  • 2. Append this script tag to the page head.
  • 3. Create a JavaScript function with the same name of the JSONP wrapping function.

The below JavaScript that will fetch the JSON file is given below:

function JavaScriptFetch() {
    var script = document.createElement('script');
    script.src = 'http://www.demo.yogihosting.com/jquery/jsonp/data1.json';
    document.querySelector('head').appendChild(script);
}

function processJSONPResponse(data) {
    alert(data);
}

Check the DEMO or DOWNLOAD the source codes:

DEMO DOWNLOAD

Conclusion

This jQuery JSONP tutorial gives you the complete knowledge of how to by-pass the Same-origin policy of web browsers. Don’t forget to check other excellent jQuery tutorials in this site.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.