Requesting a file from a different domain using JSONP

In the previous chapter, we discussed the Same Origin Policy, which prevents us from making AJAX requests to a different domain or subdomain than the one currently executing the script. JSONP is a good solution to this, and in this article we will look into it.

In the following examples, we will be making calls to a PHP script on this server, but on a different subdomain. It will output an array of two users in the JSON format and the output will be JSONP compatible because the data will be surrounded by the parameter passed to the script and a set of regular parentheses. The PHP code looks like this:
$users = array
	array("name" => "John Doe", "age" => 42),
	array("name" => "Jane Doe", "age" => 39)
echo $_REQUEST['callback'] . "(" . json_encode($users) . ")";
To see what data returned looks like, try opening the following URL in your browser:

The result will look like this:

test([{"name":"John Doe","age":42},{"name":"Jane Doe","age":39}])

If you set the callback parameter to something else, you will see that change reflected in the output. This special notation is what separates regular JSON and JSONP. Now when JSON data is returned to jQuery, it parses it into objects that you may then access and use like any other JavaScript object. For instance, the above output would result in two objects, each with a name and an age property.

Now let's try requesting the page from jQuery and use the returned data. When you test this example, notice that we call the page on a different subdomain ( than the currently executing domain (
<ul id="ulUsers"></ul>
<script type="text/javascript">
		function(data, textStatus)
        	$.each(data, function(index, user)
				$("#ulUsers").append($("<li></li>").text( + " is " + user.age + " years old"));
If you read the chapter on the get() and post() methods, you will see that there are only two main differences: The callback parameter on the URL, and the extra parameter specifying that we want the return type to be "json". The callback is set to a question mark, which will make jQuery generate a random one for us. In the script that takes the call, the value of this parameter is used, as you can see in the PHP code above.

Once we get some data back, we throw it into the each() method, which will loop over the data, each time invoking an anonymous method where we access the current set of data in the "user" variable. We then use the name and age of the user to construct a text representation, which we append to a list (ul tag) as a list item (li tag). As a result, we get an HTML list of the users returned by the script.
^ Back to Top