Best way to request data from server every x seconds - javascript

I created a very simple example. I try to request a value from my server every X seconds, in this case i simply want to get a random number, every second.
This solution works, but unfortunately there seems that an infinite loop occurs after a while, which leads to a crash. I also get over 100k Errors after a while net::ERR_INSUFFICIENT_RESOURCES.
request_data(1000);
function request_data(intervall) {
$.post('ajax.php', {
cmd: "get_random_number"
}, function (returned_data, status) {
if (status === "success") {
$("#result_output").html(returned_data);
setInterval(function() {
request_data(intervall);
}, intervall);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="result_output></p>
// ajax.php
<?php
$cmd = filter_input(INPUT_POST, "cmd");
if (isset($cmd) && $cmd == "get_random_number") {
echo rand(5, 15);
}
Whats the best solution to achieve this?

You could do a setInterval, and then inside this do an ajax call. One of the parameters you can set in the $.ajax is a timeout - so that you can stop multiple ajax calls stacking up and causing problems.
$.ajax({
url: '',
type: '',
data: {},
timeout: 3000,
success: function(data){
// do stuff
}
});
For more info on the parameters, see http://api.jquery.com/jQuery.ajax/

As Derek has pointed out, this is because, you are making 2^n calls since the setInterval is inside the function itself.
Try it like this instead
window.setInterval(1000, request_data);
function request_data() {
$.post('ajax.php', {
cmd: "get_random_number"
}, function (returned_data, status) {
if (status === "success") {
$("#result_output").html(returned_data);
}
});
}

I solved it by simply replacing setInterval with setTimeout.

Related

Ajax Set timeout every second

i am calling an ajax function every second to make an online class link live, if the class link is finished i need to display the last class until the current time matches with the scheduled class time which needs to be enabled live. so i called ajax function using set interval method, and it works fine but i am getting an error like 504 Gateway time out error and the whole site is not working. so can any one give me good suggestion please ?
Below is my ajax code
$(function() {
setInterval(updateLstream, 1000);
});
updateLstream();
function updateLstream() {
$.ajax({
type: 'POST',
async: true,
url: "../users/zbbtns_live.php",
data: {
cid: ""
},
success: function(data) {
if (data.status == 1) {
$(".setMainLiveBtn").html(data.Hdata);
} else {
//alert("No Live Streams");
console.log("ss");
}
}
});
}

Ajax running only once

I have an ajax function, and I expect it to run 1912 times, but it only runs once, for some reason. I'm using startAt, and stopAt to determine when it should stop running, but it's not working for some reason. What am I doing wrong?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function callAjax(gotoUrl, link, startAt, stopAt, output) {
$.ajax({
type: "POST",
url: gotoUrl,
data: { link : link },
error: function(xhr,status,error){
alert("error");
},
success:function(data) {
document.getElementById(output).innerHTML += startAt;
},
complete:function(data) {
startAt++;
var link = data;
if (startAt < stopAt) {
setTimeout(function(){
callAjax(gotoUrl, link, startAt, stopAt, output)
}, 100);
}
}
});
} //end of function callAjax()
</script>
<body onload = 'callAjax("test1.php", "link", 1, 1912, "output")'>
<div id = "output"></div>
Result:
1
Expected Result:
1912
The issue is on this line:
var link = data;
you are reassigning the value of link to be the returned data.
You then immediately call this inside the timeout:
callAjax(gotoUrl, link, startAt, stopAt, output)
But link isn't a link any more its an object, hence jquery errors out, and silently dies after one iteration.
Removing that line makes the code function fine, you just need to store the data in another variable and it'll work.
Here's a fiddle with the functional code with just that line commented out.

getting connection reset after sending a jquery ajax $.post

I am making a game lobby with php, jquery, ajax.
I have php echo a string that is a jquery loop that sends ajax $.post's to another page to check and see if some one joined the players game, if new users are online and to get current games to join. if there is then I fill div's on the page with the new data.
here is the loop
<script>
$(function() {
getPage = function() {
// this gets all current games users are trying to start up
$.post("lobbyClasses.php",
{
lobbyRequest: "getGames",
},
function(data, status){
if(status == "success"){
$("#joinGameContainer").html(data);
// this gets all online users and puts themin a div onlineUsers
$.post("lobbyClasses.php",
{
lobbyRequest: "getOnlineUsers",
},
function(data, status){
if(status == "success"){
$("#onlineUsers").html(data);
// start it again;
setTimeout(function(){
getPage();
}, 5000);
}else{
// get all online users failed start loop again
$("#onlineUsers").html("failed...");
setTimeout(function(){
getPage();
}, 5000);
}
});
}else{
//get all games failed start loop again
$("#joinGameContainer").html("failed...");
setTimeout(function(){
getPage();
}, 5000);
}
});
}
getPage();
});
</script>
The problem is that this loop only works sometimes and others the browser(chrome and firefox) will stall and give an error (connection reset in firefox)(no data returned in chrome) I thought that nesting the post request might help and it did significantly but it still happens from time to time. It also happens a lot more when i send another post to a different page such as the following ....
$("#makeGame").click(function(){
getGame = function() {
$("#scripts").html("getting data...");
$("#onlineUsers").html("getting data...");
$("#joinGameContainer").html("getting data...");
$("#gameContainer").html("getting data...");
//alert("newgame was clicked.");
$.post("cardgameclasses.php",
{
gameRequest: "makeGame",
},
function(data, status){
// the code stalls here and dose nothing then the browser error happens
//alert("Data: " + data + "\nStatus: " + status);
if(status == "success"){
$("#scripts").html(data);
}else{
$("#scripts").html("failed...");
setTimeout(function(){
getGame();
}, 5000);
}
});
}
getGame();
so I thought that replacing the loop with text then sending the post would help and it did a little bit but on occasion i still get a browser error connection reset. i am not sure what i am doing wrong please help.
I figured out what was going on with my code PHP only allows so many post vars to a single page to prevent denial of service attacks. I was sending too many posts. I also realized that every thing I was trying to update with ajax could be updated with a single post instead of 4 nested posts. The processing of the data can be done on server side. If you are making several posts for one page you are doing something wrong. The proper code would be this:
function myTimer() {
$.post("lobbyClasses.php",
{
lobbyRequest: "getContent1",
},
function(data, status){
if(status == "success"){
$("#lobbyContent").html(data);
}else{
$("#lobbyContent").html("failed...");
}
});
}
myTimer();
var myVar = setInterval(function(){ myTimer() }, 5000);
function myStopFunction() {
clearInterval(myVar);
}
var newarray = [];
var dateandtime = Date.now();
newarray.push(dateandtime);
function myTimer() {
if( newarray[0] + 1000 < Date.now()){
$.post("lobbyClasses.php",
{
lobbyRequest: "getContent1",
},
function(data, status){
if(status == "success"){
$("#lobbyContent").html(data);
}else{
$("#lobbyContent").html("failed...");
}
});
newarray[0] = Date.now();
}
}
myTimer();
var myVar = setInterval(function(){ myTimer() }, 5000);
function myStopFunction() {
clearInterval(myVar);
}

Why is it so hard to ping my own Server?

I got this piece of cake function:
$.ajax({
url: 'Example.html',
DataType: 'text',
cache: false,
success: function (){
alert ('Yes');
},
error: function (){
alert ('No');
}
});
This function, works just fine, BUT ONLY FOR THE VERY FIRST TIME), from the second time on, the function sends the following error to Chrome:
GET http://MyServer.com/Example.html?_=1406469092100 net::ERR_FAILED
The same situation happens equally with this second JS option:
function doesConnectionExist() {
var xhr = new XMLHttpRequest();
var file = "http://www.example.com/Example.html";
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, false);
try {
xhr.send();
if (xhr.status >= 200 && xhr.status < 304) {
alert ('Yes');
} else {
alert ('No');
}
} catch (e) {
alert ('No');
}
}
1) In the Ajax scenario I just indicate cache: "false"!
2) In the JavaScript scenario I am using random arguments to avoid cache!
Is there anything I am missing? in the Server side??
Please help...
It may be a server problem? I have created a jsFiddle and it seems to work like it should. I wrapped your $.ajax method in a ping function and run it 3 times fetching a jsfiddle resource.
function ping(i) {
$.ajax({
url: '/img/logo.png',
success: function () {
screen.log({text: 'attempt #'+(i+1)+ ' Yes', timed: +i, clear: 'no'});
},
error: function (d){
screen.log({text: 'attempt #'+(i+1)+ ' Nope', timed: +i, clear: 'no'});
}
});
}
See the already mentioned jsFiddle for output
Note: in your second code snippet your supply false as the third paramater to the open method, which means asynchronous = false, so the XHR there is synchronous. The cache: false parameter in the first snippet appends a random reuqeststring to the request. This prevents the browser from caching the fetched resource. I suppose it's not really necessary here.
After hours and hours of try an error I found the Answer....dedicated for those guys who are facing the same problem I did:
In my case this was not a common Web Page, it was an "Offline Web Page" with a Manifest File in it.
Simply in the section "NETWORK" of the manifest file included the file "Example.html" and that's it.
That's all folks!

Preventing error 503 on JQuery load

This is my code on shoutbox update :
function updateShoutbox(){
$("#shoutdiv").load("shoutbox.php", { 'action': 'update' } ,
function (responseText, textStatus, req) {
if (textStatus == "error") {
return false;
}
});
}
$(document).ready(function(){
updateShoutbox();
var auto_refresh = setInterval(
function ()
{
updateShoutbox();
$("#shoutdiv").scrollTop($("#shoutdiv")[0].scrollHeight);
}, 6000);
It returns error each some minutes :
shoutbox.php returned error:
Service Unavailable
Is there anyway to handle this error and hide it somehow ?
I edited my code so to stop showing any error on shoutbox update, but it still shows this error each minutes.
Ok, so let's take this for example:
$(document).ready(function(){
(function iterate(i) {
if (!!i) {
console.log('iteration #', i--);
setTimeout(function next(){
iterate(i);
}, 1000);
}
})(10);
});​
http://jsfiddle.net/userdude/6C8yp/
If you look at the console, you'll see it counts down until i is equal to 0, or i is not given (that's what the !! is for there). What I'm doing here is looping each second, but only after the last loop has finished. I'm feeding my loop.
Looking at what you have here, I might do this instead:
$(document).ready(function($){
var $shoutbox = $("#shoutdiv"),
timer;
(function update(){
var opts = {
url: 'shoutbox.php',
action: 'update',
complete: wait
};
$.ajax(opts);
function wait(res, status, req){
if (status == 200) {
$shoutbox
.append(res)
.scrollTop($shoutbox[0].scrollHeight);
timer = setTimeout(update, 6000);
}
}
})();
});​
http://jsfiddle.net/userdude/whsPn/
http://jsfiddle.net/userdude/whsPn/1/
Ok, so what we have above should mostly emulate the code you have in the question. You'll note that I have the complete: wait part in there, and the setTimeout() is in that callback. And.. it's only called if the status returned is 200 (success).
Now, there you could turn complete: wait to success: wait, and take out the status == 200 if statement altogether. Of course, if you do want to run the update again, but maybe do something different, this is your chance.
Also note, in the fiddle linked I've got some dummy code in there. So don't just copy/page what's in the fiddle, or you'll have errors and it won't run at all.
EDIT: Oops, found an error with url =. Fixed.
If you want to "hide" your error instead of looking for the cause of the error in the first place, try this in your callback function in the $.load:
function (responseText, textStatus, req) {
if(req.status!=200&&req.status!=302) {
return false;
}
//update the shoutbox
}
At least to me this is what seems to be the most reliable way to prevent random errors from getting through your checks.

Categories