Looping ajax calls until button is pressed - javascript

document.getElementById("uploadUpdate").addEventListener("click", function() {
intervalVarUpload = setInterval(function () {
console.log("Updating table..");
Object.keys(arrExplores).forEach(function (key) {
if(arrExplores[key][2] != "Not"){
//remoteArrUpdate makes a ajax call
remoteArrUpdate(arrExplores[key][2], key);
}
});
}, 2000);
console.log("Interval started!");
});
document.getElementById("uploadStop").addEventListener("click", function() {
clearInterval(intervalVarUpload);
});
function remoteArrUpdate(id, key) {
$.ajax({
url: 'https://offcloud.com/api/remote/status',
data: {'requestId' : id},
type: 'POST',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data) {
arrExplores[key] = [arrExplores[key][0],key,data.status.requestId,data.status.status, data.status.fileSize];
explorArrToTable();
},
error: function() {
console.log('Failed!');
}
});
}
So, at the moment, a uploadUpdate button is clicked and an interval is started to go through an array and make a ajax on every object and update that object. However, I don't want to use an interval because sometimes the next interval will start before the previous is finished and sometimes there is a long wait time. I want the next interval to start as soon as the previous interval has either successfully or unsuccessfully finished all ajax calls, to start at the beginning of the array again and start making the same ajax calls, until the uploadStop button is pressed. How would i change the two button functions to do this?

Just tried to mimic your ajax calls using a setTimeout. You could use it in your ajax success / failure. I think, you need some code refactoring to accomplish this. Hope this helps / point you in the right direction.
var intervalVarUpload;
document.getElementById("uploadUpdate").addEventListener("click", function() {
uploadUpdate();
});
function uploadUpdate() {
//Start the Interval
intervalVarUpload = setInterval(doSomething, 2000);
console.log("Interval started!");
}
document.getElementById("uploadStop").addEventListener("click", function() {
console.log("Interval Stopped");
//Clear the Interval
clearInterval(intervalVarUpload);
});
function doSomething() {
//Clear the Interval so as to hold on till the current method call is complete.
clearInterval(intervalVarUpload);
console.log("Updating table..");
var arrExplores = {
customArray: ["Yes", "Not", "Hello"]
};
Object.keys(arrExplores).forEach(function(key) {
if (arrExplores[key][2] != "Not") {
//remoteArrUpdate makes a json call
remoteArrUpdate(arrExplores[key][2], key);
}
});
}
function remoteArrUpdate(id, key) {
setTimeout(function() {
//Consider as a ajax complete
uploadUpdate();
}, 2000)
}
<button id="uploadUpdate">Upload Update</button>
<button id="uploadStop">Upload Stop</button>

Related

Ajax Iterate - Repeat the AJAX Call every 3 seconds

AJAX call instead of .click load - I would like the ajax to run every 3 seconds till the end of Total_Records. Here is my AJAX code which runs .click of a button.
I am passing two variables
1. id number
2. Total_Records
I would like the ajax to iterate a number of times = Total_Records.
Any suggestions are highly appreciated.
$(document).ready(function() {
$(document).on('click', '.show_more', function() {
var ID = $(this).attr('id');
var lim = $(this).attr('Total_Records');
$.ajax({
type: 'POST',
url: 'moreajax.php',
data: {
'id': ID,
'lim': lim
},
success: function(html) {
setTimeout(function() {
$('#show_more_main' + ID).remove();
$('.postList').append(html);
}, delay);
},
});
});
});
Method 2) Please kindly read and recommend any better way or script improvement with examples please. this will benefit everyone.
Note: I believe this method would be a great enhancement and re-usable to lots of people who are looking for interval runs.
The only issue is the cancel button .click is not stopping the ajax call.
$('#cancel').click(function() {
cancel = true;
});
$(function() {
//If cancel variable is set to true stop new calls
if (cancel == true) return;
var RecordsInterval = 10 * 1000;
var fetchRecords = function() {
console.log('Sending DATA AJAX request...');
$.ajax({
type: "POST",
url: "fetchRecords.php",
data: {
'id': ID,
'lim': lim
}
}).done(function(html) {
$('#show_more_main' + ID).remove();
$('#postList').append(html);
alert("You got it champ")
console.log('success');
console.log('Waiting ' + (RecordsInterval / 1000) + ' seconds');
setTimeout(fetchRecords, RecordsInterval);
}).fail(function() {
console.log('error');
alert("error Champ");
return;
});
}
// Fetch Records immediately, then every 10 seconds AFTER previous request finishes
fetchRecords();
});

how to recall function from controller using javascript

setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
var url = '/Lines/dbcheck/?LineID=#ViewBag.LineID&ProductID=#ViewBag.ProductID&LastID=#LastID';
var data = {};
$.get(url, data, function(response_text){
if (response_text == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
}, "text");
}
I already can call function from controller but only 1 time. I would like to create function to check the data from database and return 1 or 0. If it is 0 i would like to make a delay for 5 sec and then recall function again.
the problem is the parameter response_text is not updated because I can call the function from controller only first time
setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
$.ajax({
cache : false,
dataType: "json",
type: "GET",
async:false,
url: url ,
success: function (fdata) {
if (fdata == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
},
error: function (reponse) {
}
});
}
Your code executed immediately because of you passing () it is not wait for the time delay.
setInterval(makeAjaxCall(), 5000);
change to
setInterval(makeAjaxCall, 5000);
or alternate way
setInterval(function() {
makeAjaxCall();
}, 5000);

simple ajax request with interval

I recently began learning Ajax and jQuery. So yesterday I started to programm a simple ajax request for a formular, that sends a select list value to a php script and reads something out of a database.
It works so far!
But the problem is, that when I click on the send button, it starts the request, 1 second later. I know that it has something to do with my interval. When I click on the send button, I start the request and every second it requests it also, so that I have the opportunity, to auto-refresh new income entries.
But I'd like to have that interval cycle every second, but the first time I press the button it should load immediately, not just 1 second later.
Here is my code:
http://jsbin.com/qitojawuva/1/edit
$(document).ready(function () {
var interval = 0;
$("#form1").submit(function () {
if (interval === 0) {
interval = setInterval(function () {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}, 1000);
}
return false;
});
});
Thanks!
I might be something like the following you're looking for.
$(document).ready(function () {
var isFirstTime = true;
function sendForm() {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}
$("#form1").submit(function () {
if (isFirstTime) {
sendForm();
isFirstTime = false;
} else {
setTimeout(function () {
sendForm();
}, 1000);
}
return false;
});
});
So, use setTimeout when the callback has finished as setInterval just keeps running whether or not your callback has finished.
$(function () {
$("#form1").submit(postData);
function postData() {
var url = "tbladen.php",
data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
setTimeout(postData, 1000);
}
});
return false;
}
});
Kind of related demo

jQuery timeout function to run if a user is inactive

I've got a jQuery timeout script that runs after 30 minutes, however, it is constantly running and I only want it to run if the user has been inactive for that amount of time. How do I go about doing this?
$(function(){
var timeout = 30000;
$(document).on("mousemove", function(){
clearTimeout(timeout);
})
setTimeout(function(){
$.post("../php/logout.php", {}, function(response){
if(response.success == "1"){
location.replace("../pages/timed_out.php");
}
}, "json");
}, timeout);
})
You should reset timeout by clearing it using timeout's ID (which can be obtained as setTimeout function result) in clearTimeout and setting timeout again:
$(function()
{
var timeout = 30000;
var timer = 0;
setTimer();
$(document).on("mousemove", function()
{
clearTimeout(timer);
setTimer();
});
function setTimer()
{
timer = setTimeout(function()
{
$.post("../php/logout.php", {}, function(response)
{
if (response.success == "1")
{
location.replace("../pages/timed_out.php");
}
}, "json");
}, timeout);
}
});
If you want to reset the 'timeout', then just changing the timeout variable won't do anything. You would need to actually clear the timeout using clearTimeout()
To do this, here is what you'd need to do...
function restartTimeout() {
timeoutHolder = setTimeout(function(){
$.post("../php/logout.php", {}, function(response){
if(response.success == "1"){
location.replace("../pages/timed_out.php");
}
}, "json");
}, 30000);
}
$(function(){
$(document).on("mousemove", function(){
clearTimeout(timeoutHolder);
restartTimeout();
})
restartTimeout();
})
Take note of the fact that I assigned a variable to 'hold' the setTimeout() as that is necessary to be able to clear it.

How to change frequency of PeriodicalExecuter based on server response?

I have a reload function that reloads a page periodically. However, I would like to reload the page only if certain conditions are met (if not, increase the interval for the reload). So I tried using PeriodicalExecutor and an Ajax call like this -
<script type="text/javascript">
var nextReload = 10;
function reloadPage() {
document.location.reload();
return new PeriodicalExecuter(function(pe) {
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
var response = ...
nextReload = response.nextReload;
},
onFailure: function(){ ... }
});
this.frequency = nextReload; // doesn't do what I'd like it to do.
}, nextReload);
}
var myReload = reloadPage();
</script>
As you can see, the Ajax call returns the time (in seconds) in which the next reload should occur. However, I am not able to set the frequency of the PeriodicalExecutor to nextReload.
So how can I reload the page at variable time intervals?
Would something like this work for you?
<script>
function tryReload(){
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
if(transport == seconds){
// call self in x seconds
setTimeout(tryReload, (1000*transport));
}
else{ // transport is a URL
window.location = transport;
}
},
onFailure: function(){ ... }
});
}
//start it up!
tryReload();
</script>
Based on #Rocket Hazmat's suggestion, this worked for me -
function reloadPage() {
document.location.reload();
return new PeriodicalExecuter(function(pe) {
var that = this;
new Ajax.Request('/Task/reloadPage.htm',
{
method:'post',
parameters: { ... },
onSuccess: function(transport) {
var response = ...
nextReload = response.nextReload;
that.frequency = next;
that.stop();
that.registerCallback();
},
onFailure: function(){ ... }
});
}, nextReload);
}

Categories