I'm using PhoneGap to build an Android app. Using either jQuery or Zepto, I'm able to make calls to the website APIs using the $.ajax call. However, when the website returns a 401 (unauthorized) response, there seems to be no callback from the ajax call - none of "success", "error", or "complete" get called.
Note that the same code works fine when the response is 200 or 500.
I'm using Zepto 1.0rc1 and/or jQuery 1.7.2 with PhoneGap 1.6.1 .
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$('#button').on('touchstart', function() {
console.log("UPLOAD --- ");
$.ajax({
url: 'https://mywebsite/api/v1.0/test/?ts=' + new Date().getTime(),
type: 'GET',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth('username', 'password'));
},
success: function(data, status, xhr) {
console.log("AJAX: SUCCESS: " + data);
$('h1').text("AJAX!!");
},
error: function(xhr, errortype, error) {
console.log("AJAX: FAIL: " + errortype + " - " + error);
$('h1').text("AJAX FAIL");
},
complete: function() {
console.log("--- Complete");
}
});
return false;
});
I just had the same problem. When I get HTTP 401 back and use
$.ajax({
...
timeout: 5000, // Some timeout value that makes sense
...
});
then the error callback is called with {"readyState":0,"status":0,"statusText":"timeout"}. In that case you would have to guess that the real error is the HTTP 401.
Alternatively you can use
$.ajax({
...
async: false, // :-(
...
});
and your error callback will get something like {"readyState":4,"responseText":"<html>...</html>","status":401,"statusText":"Unauthorized"} back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With