jQuery’s JSONP Explained with Examples

Sam Deering
Tweet

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:

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Dickwan

    Many thanks for the quick and clean tips sir!

  • Pingback: Useful jQuery Function Demos For Your Projects | Layout to HTML

  • Pingback: Useful jQuery Function Demos For Your Projects

  • http://www.facebook.com/simona.adriani Simona Adriani

    So the only way yo make a jsonp request is having access to the json file… and what if you can’t change the json file and it comes to you simply in this way: {“category”: “one”,”category”:”two”} etc… ?

    • http://jquery4u.com/ jQuery4u

      Then you cannot call it cross domain unless you have a proxy pass setup or such.

  • Pingback: Problematiche cross-domain e jsonp | Blog su web design & development

  • http://www.facebook.com/keithcorcoran Keith Corcoran

    lifesaver!

  • zorg

    thanks, the jquery docs are abysmal on this

  • aaa

    tttttt

  • Dom

    After two days.. I reached this site..and it just worked out like mentioned here. Thanks a ton for the tips.

  • me

    Unsafe JavaScript attempt to access frame with URL :(

  • Pingback: 50 jQuery Function Demos for Aspiring Web Developers - Smashing Coding

  • Leonardo

    - According to the JQuery API “jsonp requests do not support synchronous operation”. So what about that async: false?
    – In the first example, if you are specifying the “jsonpCallback” parameters within the $.ajax() call I guess you don’t need to append “?callback=?” parameter in the url, am I right?

  • http://www.facebook.com/oubenal.mohcine Oubenal Mohcine

    this was very helpful, thanks a lot

  • Muhairwa Jean

    Intresting ..

  • John Schaap

    Yes I’ve been there one 2 many times. Thank you so much much for simplifying this process. :)

  • Just me

    Hi Sam,

    Thanks a lot for these code examples. I spend about half a day but with no result. When I read you article I understood how to use jsonp. Thanks!

  • Pingback: Caricamenti cross-domain con jsonp e jQuery |

  • Pingback: Useful jQuery Function Demos For Your Projects - Internet Business

  • omar salem

    awful
    simply doesn’t work

  • lse

    jsonp must run always on load of page …? or can run on press of a button?