views:

78

answers:

2

This is my code,

$.ajax({
            type:"get",

            //this doesn't work
            //url:'http://example.com/json.php',

            //But this works
            url:'http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?',

            dataType:"jsonp",
            success:function(data){
                alert('success');
            },
            error:function(){
                alert('error');
            } 
});

in json.php I have

<?php
header("Content-type: application/javascript");
?>

Then I've copied all the output of that flickr url. So the problem shouldn't be in the content of my code but how it's being sent. What do i need to fix here?

Thanks in advance!

A: 

The correct Content-type for a JSON file is:

  header( 'Content-type: application/json' );

Could that be the problem?

Lucanos
Actually I think the correct type is Javascript.
Mohammad
No - the official documentation states that it should be "application/json".See the following: - http://www.ietf.org/rfc/rfc4627.txt - http://en.wikipedia.org/wiki/JSON - http://mimeapplication.net/json
Lucanos
hmm thank you, but it doesn't work with "json" either.
Mohammad
+1  A: 

jQuery calls the success callback for JSONP requests as pointed out by Nick Craver.

Have you added the callback into your PHP script?

Take a look at this article: http://remysharp.com/2007/10/08/what-is-jsonp/

In your json.php file, you should be doing something like:

<?php
$jsonstuff = '{ something: "somethingHere" }';
echo $_GET['callback'] . "(" . $jsonstuff . ")";
?>

Since the default JSONP callback in jQuery is callback.

This is because jQuery appends a callback with an random string name (unless you specify it as jsonpCallback in the options. More information can be found in the documentation. You won't see the callback appended because it's not part of the URL, it's added by jQuery only during the execution of the $.ajax method.

You can see what I mean by trying: http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&amp;tagmode=any&amp;format=json&amp;jsoncallback=myCallBackHandler

If the handler does not execute, jQuery does not trigger the success and complete handlers specified in the $.ajax options.

sirhc
This is not accurate, the jsonp callback is just hooked up in a different way and place, it constructs a temporary function auto-named for this. The `success` function **is**, by default, that callback (this includes `complete` as well). http://github.com/jquery/jquery/blob/master/src/ajax.js#L213
Nick Craver
You're right. I've since updated my answer. Thanks, Nick!
sirhc
Hi sirhc, you're brilliant that worked perfectly!
Mohammad