3

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;
});

2 Answers 2

1

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.

-2

Downgrade phonegap. Yes. You read that right.

I tried 1.4.1: didn't work.

I tried 1.3.0: works.

So yeah, that's that.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.