Ajax running only once - javascript

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.

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");
}
}
});
}

Display a specific <div> content at setTimeout()

In the below code I am making an API call to my backend node.js app using setTimeout() which calls my AJAX at every 5 seconds. Inside my AJAX success I am displaying divContent1 & divContent2 based on certain condition which should execute at least once. After that only divContent2 should be visible at each setTimeout() calls.
index.html
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8070/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
//Some Task
}
});
$("#myButton").click(function(){
const route2 = function() {
$.ajax({
url: "http://localhost:8070/api/route2",
type: "POST",
dataType: "json",
data: { var1: val1 },
success: function (res) {
// Various tasks
if(res.flag){
$("#divContent1").hide();
$("#divContent2").show();
}
else{
$("#divContent1").show();
}
//Functions that handle div content data
},
beforeSend: function() {
$("#divContent1").hide();
$("#divContent2").hide();
},
complete: function() {
setTimeout(route2,5000);
},
});
};
$(function(){
route2();
})
});
});
</script>
The setTimeout() calls the entire route2 function which handles all the display and insertion of div content. However, the ask is to only display divContent2 from the second call.
Looking for a solution for this
The setTimeout() calls the entire route2 function which handles all
the display and insertion of div content. However, the ask is to only
display divContent2 from the second call.
You're calling route2 recursively with setTimeout(route2,5000); under complete. So this will run infinitely as complete occur each time an ajax call is completed (wether success or error). So what you can do is to create a timer and clear it after the second execution, something like this:
var ctr = 0, timer =0;
const route2 = function() {
$.ajax({
...
success: function (res) {
//Write you logic based on ctr
}
complete: function() {
if(ctr>0){
clearTimeout(timer)
}else{
timer = setTimeout(route2,5000);
ctr = ctr+ 1;
}
},
});
};
Will an external variable be enough? Just define it in the outer context and set/check it to choose the behavior:
// before declaring button click handler
var requestDoneAtLeastOnce = false;
// ...
// somewhere in success handler
success: function (res) {
if (!requestDoneAtLeastOnce) {
requestDoneAtLeastOnce = true;
// do something that belongs only to handling the first response
}
else {
// this is at least the second request, the other set of commands belongs here
}
}

Div.Show does not work when running, but does work when stepping through code

I have a div that should appear when saving. The markup for this is similar to this:
<div class="Working" style="display: none;">Message</div>
Later in my code I have some save logic, which does this:
function SaveData() {
var cancelSave = false;
$('.Working').text('Saving data ...').show();
var saveData = { 'Data': myData }; // Actually a lot of logic in here
if (cancelSave) {
$('.Working').hide();
} else {
$.ajax({
// bunch of stuff here
async: false, // tried this both ways
error: function (rsp) {
$('.Working').hide();
},
success: function (rsp) {
$('.Working').text('Saved');
$('.Working').fadeOut(5000, DoNothing());
}
});
}
}
function DoNothing() {
// Does nothing
}
If I step through the code, the div shows up perfectly when I step through the initial .show() line. However, when I run this at "full speed" ... I never see the "Saving data ..." message. The actual save does take about 5-7 seconds, so there is plenty of time to see the message.
The UI is locked up because the ajax async property is set to false. Set it to true and try it. The SaveData method will finish, update the UI to show the "saving data..." text and then update again when the ajax call returns.

Javascript - Get text from html to string

It's a php while with javascript codes. I want that this:
Check every 1 seconds that chat_status.html -text's: status = "offline"
Full code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
function loadChatStatus(){
var status = ("http://tulyita.hu/chat/chat_status.html".text);
if(status == "offline"){
//this happens 1#
} else {
//this happens 2#
}
}
setInterval (loadChatStatus, 1); //Reload file every 1 seconds
});
</script>
but it isn't worked. :( Can someone help me?
I need the text from the "chat_status.html".
function loadChatStatus(){
$.ajax({
url: "chat_status.html",
cache: false,
success: function(html){
$("#status").html(html); //Insert status into the #status div
},
});
if($("#status") == "offline"){
//this happens #1
} else {
//this happens #2
}
}
??
You can use $.get() to load the contents from your server and do something with it in the callback. Example (not tested):
$.get('http://tulyita.hu/chat/chat_status.html', function (data) {
if (data === 'chat = off' {
// happens when offline
}
else {
// happens when online
}
}, 'text');
Note that the page's current content is chat = off and not offline. Please check the exact contents of data after implementing this in your code.
Also note that your HTML page has to be on tulyita.hu or you have to add an Access-Control-Allow-Origin header because of the same-origin policy.
First, don't declare the loadChatStatus function in .ready() but outside of it. Leave only the setInterval inside the .ready() function. And 1 second is 1000 ms. setInterval expects ms.
Second, use .load() to get the contents of the url, put it in a (hidden) div,and then check what it is. You cannot just do "string".text , as a string has no .text member.

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