Home / AJAX

How Do I use JSONP to Retrieve Data from a Remote Website?

Modified on 2011/05/01 07:58 by Ralph Whitbeck Categorized as Uncategorized


How do I retrieve data from a remote website into my web forms page with jQuery?


One way to get data into your web page is to use JSON (JavaScript Object Notation), which is a lightweight data-interchange format. Here is an example.

	"jquery": {
		"website": "http://jquery.com",
		"versions": [
			{ "version": "1.5", "releaseDate": "January 1, 2011" },
			{ "version": "1.5.1", "releaseDate": "February 1, 2011" },
			{ "version": "1.5.2", "releaseDate": "March 1, 2011" },
			{ "version": "1.6", "releaseDate": "April 1, 2011" }

jQuery provides a full suite of AJAX capabilities to load data like JSON from the server without a browser page refresh.

So say the above JSON was located in a file called jquery-versions.js on the same web server as your web page we can use the ajax method to retrieve and alert that the file was loaded successfully.

	url: "jquery-versions.js",
	dataType: "json",
	success: function(data) { alert("json loaded successfully.")}

Now let’s say the jquery-versions.js file is located on Microsoft.com. If we try this:

	url: "http://microsoft.com/jquery-versions.js",
	dataType: "json",
	success: function(data) { alert("json loaded successfully.")}

The request would fail and the alert would not load. This is because we are violating an old browser policy called the same-origin policy. This policy prevents a script loaded from one domain from getting or manipulating properties of a document in another domain. The policy states that you must request a URL in the same domain of the current web page.

If we can’t request JSON from another domain how are we going to request data from a remote server? The same-origin policy does not prevent the insertion of dynamic script elements to be inserted from another domain. So we can insert JavaScript carrying JSON data in them from another domain. This technique is called JSONP

JSONP is a web service that wraps the returned JSON data in a function call. The requestor would need to accept this callback function as a request parameter, which is then executed, and the JSON extracted and ready to be used by the requestor.

Let’s revisit our earlier example:

	url: "http://microsoft.com/jquery-versions.aspx",
	dataType: "jsonp",
	success: function(data) { alert("json loaded successfully.")}

Two things changed in the above code the url needs to be some kind of web service that will handle structuring the callback function. If you try to load a JS file with just JSON you’ll get an error. Additionally, we also need to change the dataType to JSONP from JSON. Setting dataType to JSONP basically acts as a switch within the method and looks for the callback function to execute and extract the JSON.

Let’s break down the ajax call.


ajax() is a method off the jQuery object($), so you don’t need to call it after making selection. As of jQuery 1.5 there are two ways to call the ajax method.

$.ajax(url, settings);


Url is the url requested.

Settings is a key/value pair object that configure the ajax request, all options in settings are optional. The full list of settings can be found on the jQuery.ajax() api documentation page.

Here are the key options we need for our needs on a simple JSONP request.

url: if we set the url in the settings we’ll need to set the url we are requesting.

dataType: we need to set the data type we are expecting back from the server. As mentioned previously this tells the ajax method how to process the data we receive back. The available types are: xml, html, script, json, jsonp, and text.

data: data that is to be sent to the server as a key/value pair object or a string that gets added to the end of the url as a query string.

success: the callback function that executes upon successful receiving the data from the server.

Let’s put all this knowledge together into a working example. We’ll use Twitters JSON API to pull tweets from the @jquery account and display them in our web page.


Here is the HTML we’ll need.

Try Me!

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="twitter.aspx.cs" Inherits="jQueryWebForms.JSONP.twitter" %>

<!DOCTYPE html>

<html lang="en"> <head> <meta charset="utf-8"> <title>Pull in Tweets with JSONP</title> <link href="css/style.css" rel="stylesheet"> </head> <body> <form id="form1" runat="server"> <div id="page"> <h1>@jQuery</h1> <div id="tweets"> <ul></ul> </div> <div id="JSONP"></div> </div> </form> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js"></script> <script src="scripts/getTweets.js"></script> </body> </html>


$(function () { var twitterAccount = "jquery"; var url = "http://twitter.com/status/user_timeline/" + twitterAccount + ".json"

$.ajax(url, { dataType: "jsonp", data: "count=5", success: function (data) { successCallback(data); } }); });

function successCallback(data) { $.each(data, function (i, item) { $("#tweets ul").append("<li>" + item.text + "</li>"); }); };

In our success callback function we loop through each object in data and append it to our ul in our html.

In addition to the jQuery.ajax() method, jQuery also provides a shortcut method for request JSON data. $.getJSON().

$.getJSON() is shorthand for:

	url: url,
	dataType: "json", //or jsonp if the url is a remote request
	data: data,
	success: callback

Let’s look at how we can modify our ajax call above to use the shortcut method.

$(function () {
    var twitterAccount = "jquery";
    var url = "http://twitter.com/status/user_timeline/" + twitterAccount + ".json"

$.getJSON(url, function (data) { successCallback(data); }); });

All we need to do is provide a request url and a callback function to handle the data once we receive it. We don’t need to configure the request anymore then that.
  Name Size
- jsonp-twitter.png 37.92 KB