Try/Catch with jquery ajax request
Posted
by Anthony
on Stack Overflow
See other posts from Stack Overflow
or by Anthony
Published on 2010-05-11T11:12:53Z
Indexed on
2010/05/11
11:54 UTC
Read the original article
Hit count: 612
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.');
}
© Stack Overflow or respective owner