after successful ajax retry no .done - javascript

I'm making a request to a php file. The response is processed in .done(function(msg){}); and .fail this works fine. But sometimes the request gets an error. I made a retry for this. The retry also works. But if the first time fails and it is successful in de 2 or 3 try my request.done doesn't fire (in firebug I can see that is was successful)
My request:
var request = $.ajax({
url: "wcf.php",
type: "POST",
dataType: "xml",
async: false,
timeout: 5000,
tryCount: 0,
retryLimit: 3,
data: { barcode: value, curPrxID: currentPrxID, timestamp: (new Date).getTime()},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 500) {
alert('Server error');
}
this.tryCount++;
if (this.tryCount < this.retryLimit) {
$.ajax(this);
//return;
}
}
}) ;
And this is the .done and fail:
request.done(function(msg)
{
$(msg).find("Response").each(function()
{
// my code here
});
});
request.fail(function(jqXHR, textStatus, errorThrown)
{
$("#message").html(errorThrown);
});

The .done() and .fail() methods are part of Deferred Object which is implemented in the jqXHR object returned by $.ajax(). Callbacks which you register with them are not part of $.ajax() options so you can't pass them to another $.ajax(). In your code you are subscribing only to parent $.ajax() Deferred Object callbacks. To achieve the result you want, you should wrap entire operation in another Deferred Object and use .resolveWith()/.rejectWith() methods to pass the proper context. Also you need to remember that Deferred Object can change its state to resolved or rejected only once (in another words if it fails it can't succeed later). So the final code might look like this:
var request = $.Deferred(function(deferred) {
$.ajax({
url: 'wcf.php',
type: 'POST',
dataType: 'xml',
async: false,
timeout: 5000,
tryCount: 0,
retryLimit: 3,
data: { barcode: value, curPrxID: currentPrxID, timestamp: (new Date).getTime()},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 500) {
alert('Server error');
}
this.tryCount++;
if (this.tryCount < this.retryLimit) {
$.ajax(this).done(function(data, textStatus, jqXHR) {
deferred.resolveWith(this, [data, textStatus, jqXHR]);
}).fail(function(jqXHR, textStatus, errorThrown) {
if (this.tryCount >= this.retryLimit) {
deferred.rejectWith(this, [jqXHR, textStatus, errorThrown]);
}
});
}
}
}).done(function(data, textStatus, jqXHR) {
deferred.resolveWith(this, [data, textStatus, jqXHR]);
});
}).promise();
request.done(function(msg) {
$(msg).find("Response").each(function() {
//Success code here
});
});
request.fail(function(jqXHR, textStatus, errorThrown) {
$("#message").html(errorThrown);
});

Related

error "net::ERR_CERT_AUTHORITY_INVALID" in AJAX

I am trying to make an http request like:
function foo() {
$.ajax({
async: true,
crossDomain: true,
url: "https://192.168.xxx.xxx/api/Domains/GetDomains/false",
type: "GET",
contentType: false,
success: function (data, textStatus, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
}
});
}
$(document).ready(function () {
foo();
});
But Im getting error:
I tried with postman and it worked, why Im getting this error when I try via code?

Ajax Response throwing JavaScript Syntax Error

function fnValidatePCRHours(pcr, hoursEntered)
{
$.ajax({
type: "GET",
url : "/TMS/validatePCRHours.html?pcr="+pcr+"&hoursEntered="+hoursEntered,
cache: false,
success: function(data, textStatus, jqXHR)
{
alert(data);
return true;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
return false;
}
});
return false;
}
As soon as i get response (IN) from server, i get script error. Can any one help me on this?

do something at unsuccessful jquery ajax request

My ajax request is hitting an api with rate limits.
$.ajax({
url:"https://api.themoviedb.org/xxx",
crossDomain: true,
dataType: "jsonp",
dataObj : index,
success: function (response, textStatus, xhr) {
console.log('success');
}
,error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
}
});
I would like to know when I hit the rate limit.
But for the requests showing this in the console :
Failed to load resource: the server responded with a status of 429 (OK)
I don't see 'success' or 'error'.
It's like success and error are not executed.
Is there a way to popup and alert e.g. ?
I tried complete but it does not work either.
Thank you
I could not find documentation for dataObj but removing it seemed to make the query run properly.
If you get rid of it the error callback gets executed and you will be able to see error in the console.
$.ajax({
url:"https://api.themoviedb.org/xxx",
crossDomain: true,
dataType: "jsonp",
success: function (response, textStatus, xhr) {
console.log('success');
}
,error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
}
});
edit:
turns out what you actually want to change is the datatype. Unless you are explicitly also passing a callback you should tell jQuery that you are getting json and not jsonp back.
$.ajax({
url:"https://api.themoviedb.org/xxx",
crossDomain: true,
dataType: "json",
dataObj: index,
success: function (response, textStatus, xhr) {
console.log('success');
}
,error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
}
});
Try using the jQuery statusCode object in the settings, like this:
$.ajax({
url:"https://api.themoviedb.org/xxx",
crossDomain: true,
dataType: "jsonp",
dataObj : index,
success: function (response, textStatus, xhr) {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
},
statusCode: {
429: function() {
alert( "Exceeded request limit." );
}
}
});

Why jqXHR.abort() in beforeSend thorws an error?

I am trying to abort ajax call using beforeSend if certain condition is true.
As soon as I call jqXHR.abort() or return false.
I get following error
TypeError: $.ajax(...).fail is not a function
.fail(function (jqXHR, textStatus, errorThrown) {
following is the javascript code
$.ajax({
type: "POST",
beforeSend: function (jqXHR) {
if (1 === 1) {
jqXHR.abort();
}
},
data: { x:1},
url: 'echo/json'
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("error"+textStatus)
})
.done(function (data) {
console.log("ajax complete");
console.log(data);
});
jsfiddle: http://jsfiddle.net/939xG/
Does anyone know why jqXHR.abort() in beforeSend thorws an error?
or how i can change the code in beforeSend such that I can abort the ajax request without any error.
I am using jquery 1.7.2 and can not upgrade to higher version
When you abort $.ajax in beforeSend, $.ajax will return false rather than a jqXHR. Avoid it by not aborting in beforeSend, or not using done and fail methods in favor of using success and error options instead.
http://jsfiddle.net/939xG/2/
var jqXHR = $.ajax({
type: "POST",
beforeSend: function (jqXHR) {
if (1 === 1) {
jqXHR.abort();
}
},
data: {
x: 1
},
url: 'echo/json',
success: function (data) {
console.log("ajax complete");
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error" + textStatus)
}
});
console.log(jqXHR) // false
This sounds like a bug to me, but since upgrading jquery isn't an option, i didn't look into that possibility.

Where I should place return statement

I use Backbone.js and jQuery 1.7 in my application and I have some problems in building collection. In collection I have the method, which should return some object. I do "return" in $.ajax(...) success() function.
In this case i receive "undefined" instead of expected object. I understand, that the problem is in the "return" - it make success() function return some value. But I need getDomainZones() method do a return. How can I do it?
window.DmnList = Backbone.Collection.extend({
model: DmnItem,
localStorage: new Store("hosting.WhoIs"),
destroyAll: function (options) {
while (this.models.length > 0) {
this.models[0].destroy(options);
}
},
getDomainZones: function(){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
success: function(data) {
console.log(data);
return data;//problem here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
});
"Where I should place return statement"
Nowhere. You can't return the result of an asynchronous AJAX request.
Any code that relies on the data, must be called inside the success callback.
One possibility is to have your getDomainZones method receive a function that will be called when the response is received.
getDomainZones: function( callback ){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
// success: callback, // alternative if there's no other work to do.
success: function(data) {
console.log(data);
callback( data ); // invoke the function received
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
So then you'd pass a function to getDomainZones, and when the response is received, getDomainZones will invoke the function you passed, passing it the data.
getDomainZones( function( d ) {
// do something with the data
console.log( d );
});

Categories