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 w
Make sure you don't have [HttpPost] listed above your JsonResult method in your controller. This will not return data to a .getJSON call.
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.
$.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).
The json needs to be valid, otherwise the callback will not fire.
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!
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.