How to Use JSONP to Access Remote Data

  • google plus

In Brief...

In this how to, you'll learn how to use JSONP to access remote data. JSON with Padding, or JSONP, exploits a loophole in the same-origin policy which browsers employ to prevent access to resources passed via scripts from foreign sites. Instead of passing JSON-formatted data back in an Ajax call, as we do when using Ajax from within our own site, the JSONP response instead returns the JSON-formatted data as the argument of a callback function - "padded" (the "P" in JSONP) by the callback function. Most of the time, our JSONP call to the external resource specifies the name we want for the callback function; on our end, as we receive the "padded" JSON-formatted data, we then invoke the function to process the data. Without this padding -- without wrapping the JSON data in a callback function -- the security policies in place in our browsers would not allow us to access the foreign resources.


A non-JSONP Ajax call might result in the following data returned from another page on our own domain:

{ name: 'Nat' }
With JSONP, the return content might look like this:
callbackfunction({ name: 'Nat' });

On our end, we treat the returned data as a call to callbackfunction() and, if we define what callbackfunction() should do, then we can make use of the JSON-formatted data returned by the foreign server. For example:

callbackfunction = function(data){

would popup an alert displaying "Nat", since the result of our Ajax call invokes callbackfunction with a JavaScript object with name name and value Nat.

jQuery makes using JSONP quite easy, abstracting away some of the internal aspects of the remote calls, so we'll use jQuery. We'll again use jQuery's $.ajax method; there are two parameters for the $.ajax method:

  • The jsonp parameter gives the name of the callback function we wish to receive as "padding" around the returned data; for instance, jsonp: "callback".
  • The dataType parameter, which we used before, will now be jsonp.
  1. Now let's look at an example using a JSONP call to Yahoo! using their Query Language ( service.
    <meta charset="UTF-8">
    <title>JSONP - Yahoo! Query Language</title>
    <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
    	$(document).ready(function() {
    		$('#btn').click(function() {
    			var zip = $('#zip').val();
    			var query = $('#query').val();
    				url: "",
    				jsonp: "callback",
    				dataType: "jsonp",
    				data: {
    					q: "select * from where zip='" + zip + "' and query='" + query + "'",
    					format: "json"
    				success: function(response) {
    					$.each(response.query.results.Result, function(index, element) {
    						$('#Content').append('<p><a href="' + element.MapUrl + '" target="_blank">' + element.Title + '</a></p>');
    	<input type="text" id="zip" placeholder="zip"> <input type="text" id="query" placeholder="query (e.g. pizza)">
    	<button id="btn">Go</button>
    	<div id="Content"></div>
    This code renders the following in which you would enter a zip code and a type of establishment for which to search (e.g. "pizza", "movies", "supermarkets").:
    JSONP Yahoo Query
  2. We add a jQuery click handler on the button: when the button is clicked, three things happen:
    1. Local variable zip is assigned the value entered in the #zip text field.
    2. Local variable query is assigned the value entered in the #query text field.
    3. JSONP Ajax call is sent to the the Yahoo! server, and the results processed.
  3. For the $.ajax call, we specify as the url, callback is given as the name for the jsonp callback function (as required by this Yahoo! service), and dataType: "jsonp" tells the function that we expect to receive a JSONP-formatted result.
  4. The Yahoo! Query Language service offers a variety of available resources: we choose here to ask for "local" results (usually businesses). As such, as we pass - via the data parameter, a query that sends along the user-supplied zip code and query. We might, for instance, ask for all "pizza" places near a zip code like "13214" using the query select * from where zip='13214' and query='pizza'.
  5. In the success callback function -- a parameter of the $.ajax method -- we define how we will handle the response. Key here is to discover the schema by which the results are returned. Either by using a tool like Firefox's or Chrome's inspector, or by using Yahoo!'s Query Language console ( (or both), we find that the set of results in which we are interested are returned in an array "query.results.Result"; thus, our code iterates ($.each) over response.query.results.Result, appending a paragraph to #Content for each returned result: JSONP Query

More Learning Resources

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.