Spir
Spir

Reputation: 1719

jQuery & Ajax: catching a 500

I have this jQuery code that send an Ajax request on a form submit. My issue is I can't catch timeout error using that code. When I send a 500 response myself it is working but if I get a timeout then I see 500 in the console but nothing happens, the error callback is not executed. Instead I get :

SyntaxError: syntax error

On the line:

$(document).ready(function(){

Here is the full code:

$(document).ready(function(){
    $('body').on('submit', 'form#myForm', function(){
        $.ajax({
            type: "POST",
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',
            success: function(data, textStatus, jqXHR){
                alert('success!');
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('error!');
            }
        });
        return false;       
    });
});

Upvotes: 1

Views: 1429

Answers (2)

Strake
Strake

Reputation: 762

Interesting that the server is throwing a 500 and the "error" callback is not being called. To further investigate this issue add a "complete" callback to the ajax call and a timeout value:

$.ajax({
        type: "POST",
        url: $(this).attr('action'),
        data: $(this).serialize(),
        dataType: 'json',
        timeout: 5000, 
        success: function(data, textStatus, jqXHR){
            alert('success!');
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error!');
        },
        complete: function(jqXHR, textStatus){
            alert(textStatus); // this could be 'timeout'
         }
    });

The complete callback is called after the request finishes; after "success" and "error". The textStatus parameter of the complete callback will be a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). See documentation. This should give us you some further information on exactly what jquery is doing with the request.

Upvotes: 2

Ben Temple-Heald
Ben Temple-Heald

Reputation: 708

This may not be the answer you are looking for, but you can set the timeout of the ajax query to match you server, or be slightly less, and trap it, then check the textStatus.

$.ajax({
    type: "POST",
    url: $(this).attr('action'),
    data: $(this).serialize(),
    dataType: 'json',
    timeout: 3000, //3 Seconds
    success: function (data, textStatus, jqXHR) {
        alert('success!');
    },
    error: function (jqXHR, textStatus, errorThrown) {
        if (textStatus == 'timeout') {
            alert('Failed from timeout');
            //do something. 
        }
    }
});

Upvotes: 1

Related Questions