Bluefire Bluefire - 3 months ago 19
Javascript Question

Jquery AJAX error callback not being called when there is an error

I'm currently trying to implement the handling of an HTTP 413: Request entity too large error from my server. What I've done is this:

$.ajax({
url: "submit.php",
data: {
"data": POSTData
},
success: function(response, statusText, XHR) {
console.log(XHR.status + ": " + response);
resolve(); // resolve the promise and continue on with execution
},
// Added this part:
error: function(response, statusText, XHR) {
if(XHR.status === 413) {
// Request entity too large
// To solve this we split the data we want to upload into several smaller partitions
// and upload them sequentially

console.log("Error 413: Request entity too large. Splitting the data into partitions...");

// handling code below

// blahblahblah
}
},
method: "POST"
});


But instead of the error callback being fired, my console still throws an error (it says it's a 413), as if there's no handler. How do I implement this functionality?

Answer

You've got the method signature of the error callback wrong. See http://api.jquery.com/jquery.ajax/

The correct signature as per those docs is: Function(jqXHR jqXHR, String textStatus, String errorThrown)

Therefore in your case XHR.status doesn't exist because what you've called XHR is actually a string.

Try this:

 error: function (jqXHR, textStatus, errorThrown) {
    if(jqXHR.status === 413) {
        // Request entity too large
        // To solve this we split the data we want to upload into several smaller partitions
        // and upload them sequentially

        console.log("Error 413: Request entity too large. Splitting the data into partitions...");

        // handling code below

        // blahblahblah
    }
},

I strongly suspect that the error callback is being called, but because you've no code outside that if statement, you're not seeing anything.