jQuery’s JSONP Explained with Examples

OK so you are trying to load js scripts or JSON from another domain and getting that some kind of error: 404 not found error, 206 partial load error, cross domain errors etc… I’m sure we’ve all been there!

jQuery JSONP Function Demo

As you may be aware you cannot directly load data files from another domain. This is a security issue that has been around for a long time and is commonly solved by sharing data through an API, REST or such. However there are ways around this and in this post we will look at the different options available to you such as a PHP Proxy Pass but in this post we will focus on JSONP.

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.”

JSONP Requests

JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue.

Load a JSON data Object from another domain (with callback function)

What is ?jsoncallback=? used for?
Firstly you need access to the JSON file to wrap it in a “callback function”. In this case I have called it “jsonCallback”. This will be the function called by the AJAX request.

jsonCallback(
    {
        "sites":
        [
            {
                "siteName": "JQUERY4U",
                "domainName": "http://www.jquery4u.com",
                "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
            },
            {
                "siteName": "BLOGOOLA",
                "domainName": "http://www.blogoola.com",
                "description": "Expose your blog to millions and increase your audience."
            },
            {
                "siteName": "PHPSCRIPTS4U",
                "domainName": "http://www.phpscripts4u.com",
                "description": "The Blog of Enthusiastic PHP Scripters"
            }
        ]
    }
);

Now we can request the JSON via AJAX using JSONP and the callback function we created around the JSON content.

(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.dir(json.sites);
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

The output should be the JSON as an object which we can then use the data for whatever we want without restrictions.

Load a JSON data Object from other domain (no callback function)

With this method you don’t need to know the callback function name. You do however still need access to the JSON script to convert it into an Object – in this case the object is JQUERY4U.

/* Loading JSON objects using JSONP */
(function($) {
    var url = 'http://www.jquery4u.com/scripts/jquery4u.settings.json';
    $.ajax({
       type: 'GET',
        url: url,
        async: false,
        contentType: "application/json",
        dataType: 'jsonp'
    });
})(jQuery);

And the contents of the JSON file: jquery4u.settings.json.

JQUERY4U = JQUERY4U || {};

JQUERY4U.SETTINGS =
{
    "siteName": "JQUERY4U",
    "domainName": "http://www.jquery4u.com",
    "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
}

Then to access settings simple call the object JQUERY4U.SETTINGS locally in your JavaScript code.

Related Posts: