JSONP with jQuery, MooTools, and Dojo

By  on  

JSONP MooTools jQuery

We all know that the big limitation of AJAX is that cross-domain requests aren't allowed.  We also know, however, that we skirt around that rule a bit by using JSONP.  JSONP is the process of SCRIPT tag injection, referencing a cross-domain URL and providing a callback function (on your page) that the provider will call so that you can handle the result.  Let's take a look at how JSONP is handled with jQuery, MooTools, and the Dojo Toolkit.  For our examples, we'll pull tweets from Twitter with the term "Arsenal" in them.

jQuery JSONP

jQuery uses the same method for JSONP as it does for regular JSON -- the jQuery.getJSON method:

jQuery.getJSON("http://search.twitter.com/search.json?callback=?",{
	q: "Arsenal"
},function(tweets) {
	// Handle response here
	console.info("Twitter returned: ",tweets);
});

As long as a callback parameter is provided to the getJSON method, jQuery will consider the request JSONP.

MooTools JSONP

MooTools requires the Request.JSONP Class available in MooTools More.  Armed with Request.JSONP, fetching JSON from another domain is a piece of cake:

new Request.JSONP({
	url: "http://search.twitter.com/search.json",
	data: {
		q: "Arsenal"
	},
	onComplete: function(tweets) {
		// Log the result to console for inspection
		console.info("Twitter returned: ",tweets);
	}
}).send();

Request.JSONP is a super compact class too!

Dojo JSONP

JSONP with the Dojo Toolkit requires the dojo.io.script resource and its get method:

// dojo.io.script is an external dependency, so it must be required
dojo.require("dojo.io.script");

// When the resource is ready
dojo.ready(function() {
	
	// Use the get method
	dojo.io.script.get({
		// The URL to get JSON from Twitter
		url: "http://search.twitter.com/search.json",
		// The callback paramater
		callbackParamName: "callback", // Twitter requires "callback"
		// The content to send
		content: {
			q: "Arsenal"
		},
		// The success callback
		load: function(tweetsJson) {  // Twitter sent us information!
			// Log the result to console for inspection
			console.info("Twitter returned: ",tweetsJson);
		}
	});
});

Retrieving JSON with Dojo is usually done with the dojo.xhrGet method, but JSONP request this special method.  The arguments for dojo.io.script.get are the same as dojo.xhrGet with the exception of the callback parameter.

JSONP is a hugely effective, reliable, and easy to implement.  JSONP strategies also allow developers to avoid cumbersome server-side proxy writing to retrieve data.  Each of the JavaScript libraries above have battle-tested methods for retrieving JSON data across domains -- it's up to you to implement them to suit your needs!

Recent Features

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • By
    Write Simple, Elegant and Maintainable Media Queries with Sass

    I spent a few months experimenting with different approaches for writing simple, elegant and maintainable media queries with Sass. Each solution had something that I really liked, but I couldn't find one that covered everything I needed to do, so I ventured into creating my...

Incredible Demos

  • By
    Creating Spacers with Flexbox

    I was one of the biggest fans of flexbox before it hit but, due to being shuffled around at Mozilla, I never had the chance to use it in any practice project; thus, flexbox still seems like a bit of a mystery to me.  This greatly...

  • By
    Advanced CSS Printing – Using JavaScript Double-Click To Remove Unwanted DIVs

    Like any good programmer, I'm constantly searching around the internet for ideas and articles that can help me improve my code. There are thousands of talented programmers out there so I stumble upon some great articles and code snippets that I like to print out...

Discussion

  1. Cool! Thanks for sharing! :)

  2. In my plugd project I have a script.js plugin, which provides functionality similar to $.getJSON without requiring io.script (though doesn’t use the same Promises all other Dojo IO things use)

  3. For those interested, Pete’s plugd can be found at: https://github.com/phiggins42/plugd

  4. the only way i could make it work was this

    $.ajax({
      url: url,
      dataType: 'jsonp',
      data: parameters,
      mimeType:"application/json",
      complete:function(jqXHR, textStatus){
          console.log("Ajax completado. ");
      },
      success: function(data, textStatus, jqXHR){
          if(console !=undefined)
            {
                console.log(textStatus);
                console.info(jqXHR);
            }
            twitterCallback2(data);
      },
      error:function(jqXHR, textStatus, errorThrown){
          console.log("Error: "+textStatus+errorThrown);
      }
    });
    
  5. wooop. Thanks David you animal

  6. Vic

    now we still need a clever way to make POST requests using cross domain ajax calls, I think there are some initiatives around called jsonp tunnels

  7. Lolki

    Euh, what is Arsenal ?

    :) just kidding ! ;)

  8. Thomas

    It is worth noting that these examples only work as the jsonp files you are requesting are generated dynamically, that is why you need the callback=?.

    If you are trying to load in static json files, say from a CDN you will need to wrap you json data in something like this myFunction({ [ "data" : "value"] });

    Then in your js file you need your ajax call, and a function that has the same name as your wrapper in the json file.

     $.ajax({url: "http://otherdomain.com/json.json",dataType: "jsonp",cache: false,jsonp:'onJsonPLoad',jsonpcallbackString: "myFunction"}) ;
    
    // callback function
    myFunction(data)
    {
    // do stuff with the json data
    console.log(data)
    }
    

    Of course, if you have access to PHP on the server that is dishing up your JSON files you can have the jsonp file like this

    And David’s methods will work a treat.

    • Thomas

      Forgot to wrap the php bit

    • Thomas


      echo $_GET['callback'] .'({["data" : "value" ]})';

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!