JQuery ajax requests are repeated when an error occurs

I have read several posts related to this problem, but I still do not identify the problem here.

When the next function is called and a 200 response is received, everything is fine; when it encounters a 404, the ajax is repeated; adding a timeout only limits the time interval during which retry requests are made. There must be a simple reason for this, but it eludes me ...

function myFunction(ID) {
    var url = 'http://example.org/' + ID;
    var response;
    $.ajax(url, {
        success: function (responseText) {
            if (responseText !== undefined) {
              response = responseText;
            }
        },
        error: function (xhr, ajaxOptions, errorMsg) {
            if (xhr.status == 404) {
                console.log('404: ' + errorMsg);
            } else if (xhr.status == 401) {
                console.log('401: ' + errorMsg);
            }
        }
    });
    return response;
}

      

+3


source to share


1 answer


You can use the below approach to get data for your error without repetition in AJAX.

$.ajax(url, {
    success: function (responseText) {
        if (responseText !== undefined) {
          response = responseText;
        }
    },
    error: function (xhr) {
        //the status is in xhr.status;
        //the message if any is in xhr.statusText;
    }
});

      

UPDATE

You cannot return a response, because an async request and response variable will be returned to you before the actual ajax requests return a response. So I suggest you use a callback function for success using a synchronous request.



So, to get the answer, you might have a function like this:

function getResponse() {
    return $.ajax({
        type: "GET",
        url: your_url,
        async: false
    }).responseText;
}

      

Or a callback approach:

$.ajax(url, {
    success: function (responseText) {
        if (responseText !== undefined) {
            theCallbackFunction(responseText);
        }
    },
    error: function (xhr) {
        //the status is in xhr.status;
        //the message if any is in xhr.statusText;
    }
});

function theCallbackFunction(data)
{
    //do processing with the ajax response
}

      

+1


source







All Articles