oddurad
oddurad

Reputation: 417

jQuery ajax success callback not firing

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!

Upvotes: 10

Views: 16430

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117334

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"); } 
    });
}

Upvotes: 4

Related Questions