Jrgns
Jrgns

Reputation: 25197

How do I catch JSON parse errors with JQuery JSON calls?

I'm making AJAX calls to a server that sometimes return unparseable JSON. The server isn't under my control, so I can't fix that.

function eventFunction(evt) {
    $('div#status_bar').show();
    $.ajax({
        url: 'http://buggyserver.com/api/',
        type: 'GET',
        data: { 'mode': 'json', 'q': 'get/data' },
        dataType: 'json',
        success: updateForm
    });
}

function updateForm(returned, status) {
    if (status == 'success') {
        //Update the form here
    }
    $('div#status_bar').hide();
}

When unparseable JSON is returned, the updateForm functions does not get called.

How can I, on the client side, ensure that the last line of the updateForm function gets called to hide the status bar when? I've tried putting try { } catch {} clauses around both the AJAX call and the updateForm.

Upvotes: 0

Views: 1115

Answers (1)

Nick Craver
Nick Craver

Reputation: 630607

You could do this:

function eventFunction(evt) {
    $('div#status_bar').show();
    $.ajax({
        url: 'http://buggyserver.com/api/',
        type: 'GET',
        data: { 'mode': 'json', 'q': 'get/data' },
        dataType: 'json',
        success: updateForm,
        complete: function() { $('div#status_bar').hide(); }
    });
}

function updateForm(returned) {
   //Update the form here
}

The complete callback fires after success, whether it was successful or not.

Upvotes: 1

Related Questions