I'm using jQuery's $.ajax
method to fetch data from a JSONP-compatible web service and as far as getting a response and displaying the received data in my HTML, everything seems to be working fine. However, I haven't been able to get the ajax method's success callback to fire. What's even stranger is that even when I do get a valid response from the service, the error callback is always fired.
Here is an example of a simple js function I made to test this:
function doJsonp()
{
$.ajax({
url: "http://example.com/api/service?callback=blah",
dataType: "jsonp",
crossDomain: true,
success: function() { console.log("success"); }, // This is never fired
error: function() { console.log("error"); } // This is always fired
});
}
and the matching callback function:
function blah(data)
{
console.log(data); // This is called properly
}
From reading similar questions here on SO and elsewhere, it seems that this is most often caused by the service returning JSON that does not validate. For my purposes, I am using an in-house web service but have tried other JSONP services as well, such as those provided by Flickr, for example:
http://api.flickr.com/services/feeds/groups_pool.gne?id=807213@N20&lang=en-us&format=json&jsoncallback=blah
Both the JSON from Flickr's service and mine validate using jsonlint so that does not seem to be the issue as far as I can tell.
In searching for solutions to this problem, I have tried using a jQuery plugin called jquery-jsonp, found at http://code.google.com/p/jquery-jsonp/. This replaces jQuery's $.ajax
call with its own $.jsonp
so the above code looks like this:
function doJsonp()
{
$.jsonp({
url: "http://example.com/api/service?callback=blah",
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
However, the result is the same and the success callback never fires. Any help or a nudge in the right direction would be greatly appreciated!
ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.
Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the . ajaxSuccess() method are executed at this time.
define the callback-function via the jsonpCallback
-option, not inside the url:
function doJsonp()
{
$.ajax({
url: "http://api.flickr.com/services/feeds/groups_pool.gne?id=807213@N20&lang=en-us&format=json&jsoncallback=?",
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'blah',//<<<
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With