Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/Catch with jquery ajax request

I am trying to build a Google Chrome extension that makes an ajax request. Something similar to the GMail Checker extension. The problem is that when I do the request using jquery, and I put in the wrong username/password, it fails silently, with the error callback function ignored.

If I move the ajax call out of the background.html script (where I can't see the requests in the developer window), to the options.html script, I get a dialog box to re-authenticate. If I hit cancel, THEN the jquery error callback fires.

But in the original model extension (again, the Gmail checker), they use plain (non-jquery) ajax calls with a try/catch, and if I put in the wrong credentials, I get an alert saying as much.

I tried wrapping the entire jquery call in a try/catch, like so:

try {
    $.ajax({
        type: "POST",
        url: someurl,
        contentType : "text/xml",
        data: somedata,
        username: user,
        password: pass,
        success: function(data,status,xhr){
            alert("Hurrah!");
        },
        error: function(xhr, status, error){
            alert("Error!" + xhr.status);
        },
        dataType: "xml"
    });
} catch(e) {
    alert("You messed something up!");
}

But still nothing.

Is the error due to it being asynchronous, or is Chrome not returning the request as an error since it wants to re-prompt for credentials? Or do I just not know how to use try/catch?

Update

Here is a very slimmed down version of how the model code does the request:

var req = new XMLHttpRequest();
req.onreadystatechange = function() {
    try {
        if ( req.readyState == 4 ) {
            //Do some stuff with results
        }
    }
    catch (ex) {
        alert('Error parsing response.');
    }
}
try {
    req.send (data);
}
catch (ex) {
    alert ('Something went wrong with the request.');
}
like image 267
Anthony Avatar asked May 11 '10 11:05

Anthony


People also ask

How can we handle exception handling in AJAX?

This method is called when an HTTP request is successful. This method is called when an HTTP request fails. This method is called always, be the HTTP request fails or is successful. Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests.

What is jqXHR in AJAX?

The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.


2 Answers

Try something more like this, where you have a function that runs on every request once completed, regardless of what happens. This should solve the problem:

// Store a global var so we can all play nicely.

// Make sure this gets reset to false right before your AJAX call,
// or it will only work once!
var weHaveSuccess = false;

$.ajax({
    type: "POST",
    url: someurl,
    contentType : "text/xml",
    data: somedata,
    username: user,
    password: pass,
    success: function(data,status,xhr){
        alert("Hurrah!");
        weHaveSuccess = true;
    },
    error: function(xhr, status, error){
        alert("Error!" + xhr.status);
    },
    complete: function(){
        if(!weHaveSuccess){
             alert('Your username/password seems to be incorrect!');
        }
    },
    dataType: "xml"
});
like image 107
NeoNexus DeMortis Avatar answered Oct 06 '22 05:10

NeoNexus DeMortis


The ajax error callback function do not throw an exception by itself. If you want to have a try/catch you should probably throw an exception yourself inside your error function. This will trigger your surrounding catch.

PS! Sometimes you need to set the async:false parameter in the ajax call when you need to evaluate the result because by default the code will continue after the ajax request is initiated and asynchronously call the success or error callback at a later stage and only call that code.

like image 32
Stig Husby Avatar answered Oct 06 '22 06:10

Stig Husby