Search code examples
javascriptandroidjqueryajaxhybrid-mobile-app

Jquery not handle HTTP errors when the request gets failed


My problem is "simple". I'm developing a hybrid Android application that makes HTTP requests via Jquery Ajax. The problem is that when my requests gets failed(Server returns 401/403 ...etc), Jquery fires only HTTP 404 error that is not correct.

I'm making HTTP post requests like that:

    var request = $.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    data: obj,
    cache: false,
    contentType : 'application/json',
    beforeSend : function(xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
    },  
    success: function(data){
        // Success
    },
    error: function(request, status, errorThrown){

        console.log("call Login ajax failed with error, status:" + status + " errorThrown:" + errorThrown);
        console.log("call Login ajax failed with errorCode : " + request.status);

    }

The strange thing is that when i run my project as DynamicWeb project in my browser at my PC and in the url use my ip address the jquery fires the correct error events, but when i use "localhost" in the url, the jquery act as in the android devices, fires only 404 event. I tried to change jquery libary to a newest version 2.1.1 but this doesn't help. PS. I'm using jquery 2.0.2...


Solution

  • The problem for me was that server doesn't allow Cross-domain requests. So i must set "Access-Control-Allow-Origin:", "*" header in responses from my server and everything will be ok...