Jon
Jon

Reputation: 467

Getting a callback from getJSON regardless of success

I have a situation where I need to handle a potentially buggy CGI interpretter. I need to get some type of callback from a getJSON call in all circumstances. That includes bogus parameters sent to the testIt function (see below) and the CGI sending a bogus response. I thought wrapping the whole thing in a try/catch to handle the first case and adding a .done to handle the second would do the job. But my .done doesn't get called if the CGI processor outputs an invalid response. How can I ensure I always get a callback?

The code I am using is below.

function testIt() {
    try
    {
        console.log('start');
        $.getJSON(
            // URL of the server
            cgi_url,
            // pass the data
            {
                data: 'bogus',
            },
            // If the AJAX call was successful
            function() {
                console.log('worked');
            }
        )
        .done(function() {
                console.log('done');
            });
    }
    catch (err) {
        console.log('exception');
    }
}

Upvotes: 0

Views: 79

Answers (1)

Bergi
Bergi

Reputation: 664385

How can I ensure I always get a callback?

Use .always() to attach your handler! If you want to treat errors differently, use a fail handler.

console.log('start');
$.getJSON(cgi_url, {data: 'bogus'})
    .done(function() { // If the AJAX call was successful
        console.log('worked');
    })
    .fail(function() { // If the AJAX call encountered an error
        console.log('exception');
    })
    .always(function() { // When the AJAX call ended
        console.log('done');
    });

Upvotes: 3

Related Questions