jQuery
JSONP First Timer
On 26, Jun 2010 | 10 Comments | In jQuery | By abcoder
You already know ajax is one-man’s-girl, no way to make it work cross-domain(not even subdomain) due to browsers’ same origin policy security restriction. But using ajax is so sleek, you can’t even resist yourself using it under different domains. There is always a way around for everything. Do I sound contradictory? Ajax is based on the XMLHttpRequest and as long as we use it we can’t do cross-domain data transfer. Let’s think something else other than ajax.
We are used to loading images, css, javascript files from other domains and it’s okay if we use any server-side dynamic link as the src, this is a common phenomena on web. For example:
<script type="text/javascript" src="http://www.other-domain.com/dynamic-js.php?id=5&name=Matt"></script>
There is no security restriction including javascript source from different domains, and fortunately enough you can pass GET variables (don’t over-expect for POST) with the url. This is how JSONP (JSON with padding) works, thanks to the open policy for <script> tag. May be you’r already thinking how to implement this idea, hold on! you don’t need to reinvent the wheel.
Here comes jQuery’s $.getJSON(), with this function you can pass url of another domain and get JSON data. Lemme warn you, for the very first time most of you won’t be able to make it work. Here is an example:
$.getJSON("http://www.other-domain.com/dynamic-js.php?id=5&name=Matt&jsoncallback=?",
function(data){
// your code goes here
});
You need to understand this “jsoncallback=?” bit clearly. From your firebug Net panel you can see the “?” is replaced with “jsonp1277557614558″ (random value on each request).

The common mistake you’re gonna do is you expect to see something on firebug’s Console tab, but nothing there, once again JSONP is NOT Ajax request. This is merely an external javascript file being added to your document dynamically, if you don’t believe me on your firebug panel click the JS from Net tab to filter out the JS only(marked in the screen-shot above). You’ll definitely see the JSONP url there. This is the client-side part of $.getJSON(). The confusion still remains with the server-side code.
Back to “http://www.other-domain.com/dynamic-js.php?id=5&name=Matt&jsoncallback=?”, the file being called is dynamic-js.php. Put this one line of code in that file:
<?php print_r($_GET); ?>
And check the Response output from firebug’s Net tab. It’ll be something like:
Array
(
[id] => 5
[name] => Matt
[jsoncallback] => jsonp1277557614558
)
In Ajax when the dataType is json the response from server-side script is just the json string:
{
// your json data
}
Here is the most important part, unlike ajax for JSONP the $.getJSON() expects the response like:
jsonp1277557614558({
// your json data here
})
So you must wrap the json output with jsonp1277557614558( ). If you don’t do it the callback will fail silently without any error, which makes it tough to detect the exact problem. Remember the jsonp1277557614558 is a random string. For php the code will be something like this:
<?php
// your code here
// get the output in an array say $output_array
$jc = $_GET['jsoncallback'];
echo $jc . '(' . json_encode($output_array) . ')';
/*
// For ajax response, simply
echo json_encode($output_array);
// is enough
*/
?>
This is the most crucial thing, most programmers do the mistake for their very first time as there is no clear elaboration on $.getJSON documentation page. FYI, json_encode() function is not available on older version of php. You can get the php class from json.org.
Hope your $.getJSON() is now working!
Comments, criticism are most welcome.
-
Very well written, keep it up. First time I also got stuck with this same problem. getJSON() is a really cool function of jquery for cross-domain communication.
-
Thank you David for sharing your experience..
-
For first timer, I think $.jsonp() would be preferable seeing as it supports a lot more than $.getJSON().
-
I see, thanks for the link.
-
thank you very much it was very useful
-
I will be wondering generate an income might be advised whenever a brand new post has been created.
-
Thanks for sharing JSONP First Timer with us keep update bro love your article about JSONP First Timer .
-
Here is simple way for the Dot Net Version:
Client Page:
$.getJSON(“http://urltocall.com/ProductWebService.aspx?ItemIDs=23329&CallBack=?”,
function(data) {
debugger;
alert(“Hi I Received response for my request “);
// your code goes here
});// YOU CAN CONFIGURE THIS SCRIPT IN PAGE OR A JAVASCRIPT… YOUR WISH..EITHER YOU CAN CAL IT WITHIN A FUNCTION
ProductWebService.aspx
————————————-
protected void Page_Load(object sender, EventArgs e)
{var callBackName = Request.QueryString["CallBack"];
var itemIDs = Request.QueryString["ItemIDs"];var stringJSON = “{“Status”:”Success”}”;//Whatever JSON format response
var callBackFunParams = callBackName + “( ” + stringJSON + ” );”;
Response.Write(callBackFunParams);
Response.End();}
-
Might I just say nice to read a alleviation to discover person who really knows what they may be discussing on the web. You certainly get experience to bring an issue to light and enable it to be necessary. More people need to study it and know it all side of the story. I cannot believe you’re not more popular because you essentially have the gift.
Submit a Comment
© Copyright 2012 ABCoder |













Comments