Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

callback function doesn't work when using getJSON function in jQuery

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.

like image 427
Elias Zamaria Avatar asked Apr 20 '09 22:04

Elias Zamaria


2 Answers

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

like image 108
karim79 Avatar answered Oct 11 '22 15:10

karim79


$.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).

like image 40
Peposh Avatar answered Oct 11 '22 15:10

Peposh