views:

265

answers:

2

Hi!

I have an jQuery JSON request, that loads some JSON from another server (ex. foo.com):

$.getJSON("http://foo.com/json.php",function(data) { alert(data); });

But I receive data as null. This is not cross-domain issue, I tried following:

$.getJSON("http://twitter.com/users/usejquery.json?callback=?",
    function(data) { alert(data); });

and received nice JSON object. So, I think there is problem with backend, Apache 2.2.14. Here are HTTP headers, sent from server:

Date: Sun, 07 Mar 2010 16:08:38 GMT
Server: Apache/2.2.14 (CentOS)
X-Powered-By: PHP/5.3.1
Content-Length: 2
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: application/json; charset=UTF-8

The headers are the same in each case: regular HTTP-request or AJAX. But I receive empty content with AJAX, and normal JSON with browser request. I'm using Firebug for tests, PHP5 for forming JSON.

Somebody have any ideas? Thank you!

+3  A: 

I'm pretty sure that in order to do cross domain calls like this you have to have a callback, it's what's needed to do JSONP.

here is some more info on jsonp http://www.insideria.com/2009/03/what-in-the-heck-is-jsonp-and.html

For jsonp to work you have to have a callback for the server to wrap the json string in. for example:

$.getJSON("http://foo.com/json.php?callback=?", function(data){});

here a callback function is generated by jquery and passed into the request, so it would be something like:

http://foo.com/json.php?callback=generatedFunction

then what's returned by the server should be:

generatedFunction("{key:value, key2:value2}");

where the parameter in that function is the actual json string.

in the php to return this it would be something like:

$callback = $_GET['callback'];
print($callback."(".json_encode($theobject).");");
John Boker
If you don't provide a callback function, jQuery will make one for you and from it call the callback provided in the "getJSON" call. That's kind-of the whole point to the "getJSON" API :-)
Pointy
dont you still need to have the callback=? in the url? otherwise how does the server know how to wrap the json object?
John Boker
jQuery sets all that up for you automatically. It makes a little function with a unique name (using an internal counter), and uses that in the URL. That function calls the callback provided to "getJSON". (I need to check the source again to make sure that I am not making a fool of myself here, but I was just reading the code a couple of days ago.)
Pointy
the server still needs to process the request using the generated function, you cant just return json from the server, it has to be wrapped in that function;
John Boker
Pointy, you are right, jQuery automatically adds smth lik ?_8567344543 to URL.
Andrew Bashtannik
A: 

More about cross-domain JSON throw JSONP and jQuery.

Andrew Bashtannik