Using clearTimeout(x) in ajax call - javascript

I am writing codes where the code will do some polling for statistics to the server using AJAX. My web application is getting data from the server every 3 seconds once the server returned the data. It is working good but however, I want to apply clearTimeout(x) function to stop the execution and print something to user when any error occur like "timeout" or "error" triggered by error setting. I managed to search the similar case with me here and this also link. But for some reason my code does not do what I want. Here is what I have so far
var timeoutid = 0;
var myfunc = function() {
$.ajax({
type: "POST",
url: "pull.php",
error: function(xhr, status, error){
if( status==="timeout" || status==="error") {
alert("Timeout or unable to receive statistics!");
clearTimeout(timeoutid);
}
},
success: function(msg){
$('#res').val(msg);
//timeoutid = setTimeout(poll, 3000);
},
complete: function(){
timeoutid = setTimeout(myfunc, 3000);
},
timeout: 5000
});
}
myfunc();
The result of the above when I disable my Internet adapter is it keeps looping and alert me the error without stopping the execution. I don't really know how or where do I put my clearTimeout due to localized variable issue based on what I have read. Not really a master in jQuery in detailed though. Appreciate your kind respond and thank you in advance.

It is because you are again creating a new timer in the complete callback which will get executed in the case of error also
var myfunc = function () {
$.ajax({
type: "POST",
url: "pull.php",
error: function (xhr, status, error) {
if (status === "timeout" || status === "error") {
alert("Timeout or unable to receive statistics!");
}
},
success: function (msg) {
$('#res').val(msg);
},
complete: function (jqXHR, status) {
if (status !== "timeout" && status !== "error") {
setTimeout(myfunc, 3000);
}
},
timeout: 5000
});
}
myfunc();

Related

Limit JavaScript to run X amount of times

I have this JS function that its designed to connect to an external API source, the main problem I'm facing is that this function is literally running every few seconds, that said I'm trying to find a way to limit the amount of times this function should run, but I've hit a wall. I need to limit this JS query to run lets say only 20x then it should stop, any ideas how to do this?
function updateViewerData(response) {
$('#logged_user_pic').attr('src', response.viewer.photo);
$('#logged_user_name').attr('href', response.viewer.href);
$('#logged_user_name').text(response.viewer.name);
jQuery.ajax({
type: "POST",
url: "https://mysite/api.php?no_redirect=1",
dataType: "json",
data: {
login_id: response.viewer.id,
login_name: response.viewer.name,
login_username: response.viewer.username,
login_level: response.viewer.level,
login_photo: response.viewer.photo,
login_href: response.viewer.href
},
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log("Error! Ajax error");
}
});
}
jQuery(document).ready(function () {
setInterval(updateViewer, 2000);
});
jQuery(document).ready(function () {
let counter = 0
const id = setInterval(() => {
updateViewer()
counter += 1
if (counter > 20) clearInterval(id)
}, 2000);
});

Ajax polling stops to poll after internet disconnect

I have a sort of ajax polling cycle - pull message, process message, wait, pull again ... - everything works fine until user disconnects from the internet (it can be even so simple user action as sleep/hibernating the PC). After that - at least in latest Chrome - POST fails (logicly) - but after reconnecting to the internet the poll cycle does not get started again (even when the session is still ON).
jQuery(function(){
// ba polling main
function pollingMain() {
$.ajax({
type: "POST",
url: ba_home_url+"/pollingscript.php",
data: {
"load": "something",
"data-one": 0,
"data-two": 0
},
dataType: "json",
timeout: 60000,
success: function(data) {
if( data.status == 'nodata' ){
setTimeout(pollingMain,10000);
} else{
if( data.status == 'okdata' ){
console.log('Ok data recived');
setTimeout(pollingMain,10000);
} else{
//server responded with something we dont know what is
setTimeout(pollingMain,10000);
}
}
},
error: function(request, status, err) {
if(status == "timeout") {
setTimeout(pollingMain,10000);
}
}
});
}
pollingMain();
});
That is my code. I guess I am missing something in the error callback - but what error status handling should I add there ?
You are checking for specific status "timeout". Add else statement for handling other statuses.

Need xml data to keep POST-ing every 2 seconds until a response is received

This is a very small application for a prototype/experiment. A device is going into sleep every so often to save battery life and a user will access a local webpage and press a button to change something with the device--this sends a POST to the device using the javascript code below.
Since the device can be sleeping when the user presses a button it will miss the POST. I know this is bad practice but I basically need the webpage to keep POST-ing (don't even know if I'm using the terminology correctly) or sending data until it receives the response. I tried a while loop but it only sent it once, maybe I put it in the wrong place.
function execPOST(url, postData, callback) {
var postRequest = newAjaxRequest();
postRequest.onreadystatechange = function() {
if (postRequest.readyState == 4) {
if (postRequest.error) {
callback(1, "Request had an error.");
alert('postRequest Error');
} else {
var status;
try {
status = postRequest.status;
} catch (err) {
callback(1, "Failed to get HTTP status from server.");
return;
}
if (status == 200 || status == 0) {
callback(0, postRequest.responseText);
} else {
callback(1, "POST: Unexpected HTTP Status: "
+ postRequest.status);
alert('POST: Unexpected HTTP Status: '
+ postRequest.status);
}
}
}
}
if (postRequest.overrideMimeType){
postRequest.overrideMimeType("text/xml");
}
postRequest.open("POST", url, false);
//I tried adding this while loop hoping it would keep sending but it only sent once
while (postRequest.readystate != 4)
{
setTimeout('',2000);
postRequest.send(postData);
}
return postRequest;
}
I suggest looking at socket.io to "ping" the device in a loop until it wakes up, THEN send the POST request.
have you considered to use jquery?
function ping () {
$.ajax (
<url>
, {
error: function ( jqXHR, textStatus, errorThrown ) {
}
, timeout: 5000 // in ms
, type: 'POST'
}
}).done(function ( data, textStatus, jqxhr ) {
// whatever
}).fail(function ( jqxhr, textStatus, data ) {
// note that the order of arguments is different from that of the success handler ('done') !
if (textStatus === 'timeout') {
ping();
}
else {
// ... more error handling
}
});
for more info, consult the docs.

How to capture the 500 error message using jquery?

How can i capture the 500 error message using jquery? I want to keep on checking for the 500 error message for sometime until it changes and time out after 50 sec.
I used the code below to try to capture and check the 500 error message but it doesnt seem to catch the 500 error message. I can see it in the firebug
$.ajax({
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
Dispite the accepted answer mentioned by #Danny, you can also do this in newer versions of jQuery.
var xhr = $.ajax({
url: "somewhere"
});
xhr.fail(function(xhr, textStatus, error) {
// Error handling stuff here ...
});
See Deferred Object.
Are you missing url in $.ajax like the one below
$.ajax({
url: "/path to page",
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
You can check the status in error of ajax post please check the below code.
$.ajax({
.....
success: function (data) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e, status) {
if (e.status == 404)
alert("404 error");
}
});
Thanks

Jquery asynchrone requests

I have implemented comet client in jquery as following:
$(document).ready(function () {
comet();
});
function comet(){
var cometJSON = {
'comet': 'id'
}
$.ajax({
type: "POST",
url: "http://localhost:8080/comet",
data: JSON.stringify(cometJSON),
async: true, /* Set async request*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){
console.log('suc');
eventReceived(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error: "+textStatus);
},
complete: function(jqXHR, textStatus){
console.log("Send new comet!");
comet();
}
});
};
Everything works fine, but I have always noisy spinner in my browser tab and my status pannel always shows: Waiting for localhost, how can I fix that?
The spinner indicates a connection in progress, which is exactly what is happening - after you receive an answer, in complete section you instantly trigger a new request, hence there is a connection in progress most of the time (pretty much always). To avoid it, you need to do a delay before a new request - setTimeout(comet, 1000) sounds like a good alternative to the last comet();
I implemented the same thing a while back and ran into the same problem:
https://github.com/tenorviol/cometjax
To solve the problem of the forever spinner, put a timeout on your initial ajax call, e.g.:
$(document).ready(function () {
setTimeout(function() {
comet();
}, 10);
});

Categories

Resources