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.

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 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 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 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 kept in other domain using JSONP method.

Fetch JSONP using JavaScript

We 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);
}

DEMO DOWNLOAD

Conclusion
Thank you for visiting this jQuery JSONP tutorial. There are many more jQuery tutorials which you can read – the links are given below.

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.