18

I am trying to use the getJSON function in jQuery to import some data and trigger a callback function. The callback function doesn't run. However, if I try the same thing with the get function, it works fine. Strangely, it works with the get function even when I pass "json" as the type. Why is this happening? I tested the following file in Firefox 3 and IE 7:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<title>ajax test</title>
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
</head>
<body>
<input type="button" id="test1" value="get">
<input type="button" id="test2" value="getJSON">
<input type="button" id="test3" value="get with json type">
<script type="text/javascript">
$("#test1").click(function() {
    $.get("index.html",
        function(response) {
            alert('hi');
            //works
        }
    )
});

$("#test2").click(function() {
    $.getJSON("index.html",
        function(response) {
            alert('hi');
            //doesn't work
        }
    )
});

$("#test3").click(function() {
    $.get("index.html",
        function(response) {
            alert('hi');
            //works
        },
        "json"
    )
});
</script>
</body></html>

This seems to happen no matter what URL I access, as long as it's on the same domain. I tried passing some data and that doesn't make a difference.

Of course I can work around the problem by using the get function like I did in my 3rd test function, but I am still curious as to why this is happening.

I know there is a similar question asked here but it didn't answer my question.

Community
  • 1
  • 1
Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
  • Could it be that the json is badly formed? – karim79 Apr 20 '09 at 22:47
  • Maybe I should have been more clear. index.html is the file I posted above. I am just trying to access the document itself, which is not the most useful thing. I just put that there because it was simple and convenient. Again, it doesn't seem to matter what I put for the URL. Does the json need to be valid? – Elias Zamaria Apr 20 '09 at 22:49
  • It may sound silly for me to ask if the json needs to be valid, but if it does, why does the 3rd test function work even without valid json? – Elias Zamaria Apr 20 '09 at 22:51
  • Try using some valid json to test, see what happens. – karim79 Apr 20 '09 at 22:54

8 Answers8

24

The json needs to be valid, otherwise the callback will not fire.

karim79
  • 339,989
  • 67
  • 413
  • 406
4

$.getJSON() is JSONP, so change it this way:

$("#test2").click(function() {
    $.getJSON("index.html?callback=?",
        function(response) {
                alert('hi');
        }
    )
});

Server receives param callback filled with something like: jsonp1291077863309. In a response write back callback function jsonp1291077863309( PUT_JSON_HERE).

Peposh
  • 172
  • 7
3

Right! After 2 days getting crazy trying to make $.getJSON to accept a well-formed JSon string from the server, the problem was really on the server! Just like Carl_Platt says, you have to prepend the callback value received as a url parameter to the json output ($_GET['callback'] in PHP). That's called "JSON-P output", just in case you want to google about it.

Hands on, here a page where they show the solution in PHP:

http://1080d.com/lang/en-us/2009/10/converting-php-to-jsonp-with-json_encode/

And remember (really important) to add to the url you call the callback=? parameter! (Only needed if the url you are calling is not in the same server serving the executing jquery script)...

JQuery will automatically replace '?' with a convenient value before sending it to the server. You don't need to worry about which value is used, it will all be seamless for you (if the server makes the right job! And that was the problem in my case!) :-)

Hope it helps!

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
  • Thank you very much! fortunately for me I haven't been trying for a couple of days, but at least a couple of hours, and this was EXACTLY what I needed to do to fix it! – Tarka Nov 29 '11 at 19:53
0

Make sure you don't have [HttpPost] listed above your JsonResult method in your controller. This will not return data to a .getJSON call.

WEFX
  • 8,298
  • 8
  • 66
  • 102
0

I had the same issue despite having well formed JSON etc. I was able to query my webservice, and get a response, however, my callback function wasn't firing. After scrounging the net, i most interwebers suggested using 'jsonp', which i did since my app performs some cross domain calls, and also added 'callback?' to my url. This didn't work but that including the callback with the returned JSON solved my problem. The code below explains what i mean:

//server side json formed somewhere up here
String data = callback + "("+ json +")" ;

the response resulting from this is something like "jsonp1280403476086([{"Name":"Jack Sparrow" which jQuery seemed to not have a problem and so never died on me.

Hope this helps.

emilio
  • 314
  • 3
  • 16
0

Use $.post instead of $.getJSON(), in MVC2 if you are using $.getJSON or $.get be sure to set JsonRequestBehavior to AllowGet. Else this will return HTML error that causes your requst not to trigger the callback.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Rod
  • 11
  • 1
0

Under the surface, when you call getJSON, this is what's happening:

// ~ line 3216
getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
}, // ... rest of jQuery core

So there must be some other thing preventing the callback from firing...

I would start by **alert**ing different things (not just 'hi') on each callback, that way you know which one is failing/succeeding.

James
  • 109,676
  • 31
  • 162
  • 175
0

As mentioned by numerous others, you need valid JSON (i.e. complies with the rules at http://json.org/) for getJSON to work (this means you cannot get HTML via getJSON as in your example).

The reason the last test works is because the last parameter "json" is not being interpreted as the "type". Because the following does NOT work:

$("#test3").click(function() {
    $.get("index.html",
        '',
        function(response) {
                alert('hi');
                //works
        },
        "json"
    )
});
grammar31
  • 2,000
  • 1
  • 12
  • 17