I've read through several posts related this this kind of issue, but I'm still not identifying the issue here.
When the following function is called and receives a 200 response, all is well; when it encounters 404 the ajax is repeated; adding a timeout only limits the time frame during which the repeat requests are made. There has to be a simple reason for this, but it is eluding 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;
}
You can use the below given approach to get the 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 the response because you have an async request and response variable will be returned before the actual ajax requests gives a response. So I suggest You either use a callback function on success ore use a synchronous request.
So to get the response you can have a function like so:
function getResponse() {
return $.ajax({
type: "GET",
url: your_url,
async: false
}).responseText;
}
Or the callback approach is:
$.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
}