set and clear interval by ajax - javascript

I simply want to clear previous interval and set a new one when an ajax call is made.
The current code is:
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: {
'title': title
},
dataType: 'json',
success: function (data) {
var interval = null;
if(data.count_down){
var _second = 1000;
var _minute = _second * 60;
var timer;
var end = data.count_down
mins = Math.floor(end / 60);
secs = end % 60;
var interval = setInterval(count,1000)
function count(){
console.log(parseInt(secs))
secs -= 1
}}
else{
var stop = function(){
clearInterval(interval);}
}
}
})
})
I tryed many recommended variations to be able to clear the interval from outside of the function. Such as;
setting the "interval" variable to null or to false,
window.setInterval,
writing the count function inside of setInterval,
writing the count function as a separate function outside of the ajax function,
But neither of the variations cleared the interval.
Later on I'll also need to clear the interval on keydown.

From your code, I will do like below (P.S. didn't test):
var interval = null,
secs = 0;
function count() {
console.log(secs);
secs -= 1;
}
function deal_data(data) {
if(interval == null && data.count_down){
var end = data.count_down
secs = end % 60;
interval = setInterval(count, 1000);
else if (interval != null) {
clearInterval(interval);
}
}
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: { 'title': title },
dataType: 'json',
success: function (data) {
deal_data(data);
}
})
})

After several changes to MarshalSHI's answer the code ended up like this:
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: { 'title': title },
dataType: 'json',
success: function (data) {
deal_data(data);
}
})
})
var interval = null;
function deal_data(data) {
if(interval == null && data.count_down){
var end = data.count_down
secs = end % 60;
interval = setInterval(count, 1000);}
else if (interval != null) {
clearInterval(interval);
interval = null;
}
}
function count() {
console.log(secs);
secs -= 1;
}

Related

JavaScript Increment number every time (if statement) is true

In my code I am retrieved data from the data base every 30 seconds using AJAX. I want to use JavaScript to increment variable wht every time data is received from the database (every 30 seconds) and when if statement is true. Below code is working and incrementing to 1 but it doesn't go above 1. Does anyone has a solution for this problem?
<script>
$(document).ready(function () {
ajax_call = function() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white){
var wht = (function(w) {
return function() {
w += 1;
return w;
}
}(0));
document.getElementById("memo").value = wht();
}else{
console.log("Color is not white");
}
var interval = 30000;
setInterval(ajax_call, interval);
});
</script>
<script>
const minusButtonFw = document.getElementById('memo-minus');
const plusButtonFw = document.getElementById('memo-plus');
var memo = document.getElementById('memo');
minusButtonFw.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(memo.value);
memo.value = currentValue - 1;
});
plusButtonFw.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(memo.value);
memo.value = currentValue + 1;
});
</script>
First of all your variable wht is a function. If you simply want to keep track of the number of time the if conditions is true you can do it by making the variable static (literaly). you can achive this by storing the variable in a global scope.
Also there are sytax errors in your code too where wht is defined.
try this
$(function () {
var memo = document.getElementById("memo");
memo.val = 0;
var ajax_call = function () {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white) {
memo.val++;
memo.value = memo.val;
} else {
console.log("Color is not white");
}
}
});
}
var interval = 30000;
setInterval(ajax_call, interval);
});
A Note:
If the response is managed by you, I would recomend sending the response as json rather than simply sending it as an html with just one value color.
You'll need to keep track of "w". Your current setup is using "w" as a parameter to a function. You'd need to keep it outside of the function and increment it from inside the function. You'll also need to wrap that function in an interval Something like the following:
var w = 0;
function setWhite(color) {
if (color == white) {
w++;
document.getElementById("memo").value = w;
} else {
console.log("Color is not white");
}
}
setInterval(function() {
setWhite(color);
}, 30000);
This should give you what you want. I didn't run the code so there are probably syntactical errors that you'll need to correct.
Try change the line
document.getElementById("memo").value = wht();
to
document.getElementById("memo").value = wht(document.getElementById("memo").value);
Your full code:
<script>
$(document).ready(function () {
ajax_call = function() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white){
var wht = (function(w) {
return function() {
w += 1;
return w;
}
}(0));
document.getElementById("memo").value = wht(document.getElementById("memo").value);
}else{
console.log("Color is not white");
}
var interval = 30000;
setInterval(ajax_call, interval);
});
</script>
I made an example with setInterval. I made w global so it will work. Try this:
var w = 0;
var interval = setInterval(function() {
if (color == white) {
w++;
document.getElementById("memo").value = w;
} else {
console.log("Color is not white");
}
}, 30000);

How to run a function that a on form submit ajax with automatic click button

I am trying to submit a form with just automatic click button.
so I have a timer which is if the timer is already 0, it should submit the form automatically.
here is the code that I have.
function tick() {
var timeDisplay = document.getElementById('question_timer');
var isTimeLimit = true;
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
if (sec < 10) {
sec = '0' + sec;
}
var message = min.toString() + ':' + sec;
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0 && isTimeLimit == true) {
clearInterval(intervalHandle);
displayQuestion();
} else {
//boolean is false
if (secondsRemaining === 0) {
submitAnswer();
clearInterval(intervalHandle);
}
}
secondsRemaining--;
}
function startCountdown() {
clearInterval(intervalHandle);
secondsRemaining = 5;
intervalHandle = setInterval(tick, 1000);
}
function submitAnswer() {
$('#form_question_scenario').on('submit', function(e) {
$.ajax({
method: "post",
url: url,
data: new FormData(this),
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
});
}
How can I run the submitAnswer function if the timer is already 0. any help would be really appreciated.
The submitAnswer() function just attaches the event handler, it doesn't actually submit the form.
To achieve what you require attach the submit event handler when the page loads, then when you want to submit the form trigger that event on it. Try this:
// attach submit event handler when the page loads
$('#form_question_scenario').on('submit', function(e) {
$.ajax({
// ajax settings here...
});
});
function tick() {
var timeDisplay = document.getElementById('question_timer');
var isTimeLimit = true;
var min = Math.floor(secondsRemaining / 60);
var sec = ('00' + (secondsRemaining - (min * 60))).slice(-2); // note tidied the logic here
var message = min.toString() + ':' + sec;
timeDisplay.innerHTML = message;
// stop if down to zero
if (secondsRemaining === 0 && isTimeLimit == true) {
clearInterval(intervalHandle);
displayQuestion();
} else {
if (secondsRemaining === 0) {
$('#form_question_scenario').trigger('submit'); // submit the form here
clearInterval(intervalHandle);
}
}
secondsRemaining--;
}
function startCountdown() {
clearInterval(intervalHandle);
secondsRemaining = 5;
intervalHandle = setInterval(tick, 1000);
}
You don't need submit event at all, just call the function like you did when 0 sec is left, get id of form and create new form data, and do Ajax request...
function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
$.ajax({
method: "post",
url: url,
data: new FormData(myForm),
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
EXAMPLE:
Form data is populated without submit event just by calling the function:
function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
let data = new FormData(myForm)
formObj = {};
for (var pair of data.entries()) {
formObj[pair[0]] = pair[1]
}
console.log(formObj)
}
submitAnswer()
<form id="form_question_scenario">
<input type="text" value="test" name="test">
</form>

stop the timer function from executing when form is submitted

I have an online quiz program where user needs to complete it within a time period. When user runs out of time,I show an alert saying that your time is up and he is redirected to result page. I get the same alert when user completes the quiz before the time expires and is inside result page. I have modified the code like following but its not working. I am calling the function initTimer(1,1) inside an ajax requested page named questions.php.
In index.php
function initTimer(periodInSeconds, status) {
if (status == 0) {
return false;
}
var end = Date.now() + periodInSeconds * 1000 * 60;
var x = window.setInterval(function() {
var timeLeft = Math.floor((end - Date.now()) / 1000);
if (timeLeft < 0) {
clearInterval(x);
alert("Time's Up!");
timeExpired = true;
var completed = 1;
$.ajax({
type: "POST",
url: "success.php",
data: {
'userID': <?php echo $_SESSION['userID'];?>
},
success: function(hasil) {
$('.response_div').html(hasil);
}
});
}
$(document).find('#timerspan').html('00:' + (timeLeft < 10 ? '0' + timeLeft : timeLeft));
}, 200);
}
//when user submits the form before time expires
$(document).on('submit', '.form_choice', function() {
initTimer(1, 0)
$.ajax({
type: "POST",
url: "result.php",
data: data,
success: function(hasil) {
$('.response_div').html(hasil);
}
})
});
I dont want the init function() to execute when user submits the form before time expires.Please help me
Declare the variable holding the timer outside the initTimer function, then you can clear the timer by calling it with status = 0
var timer;
function initTimer(periodInSeconds, status) {
if (status == 0) {
clearInterval(timer);
return;
}
var end = Date.now() + periodInSeconds * 1000 * 60;
timer = window.setInterval(function() {
var timeLeft = Math.floor((end - Date.now()) / 1000);
if (timeLeft < 0) {
clearInterval(timer);
alert("Time's Up!");
timeExpired = true;
var completed = 1;
$.ajax({
type: "POST",
url: "success.php",
data: {
'userID': <?php echo $_SESSION['userID'];?>
},
success: function(hasil) {
$('.response_div').html(hasil);
}
});
}
$(document).find('#timerspan').html('00:' + (timeLeft < 10 ? '0' + timeLeft : timeLeft));
}, 200);
}
//when user submits the form before time expires
$(document).on('submit', '.form_choice', function() {
initTimer(1, 0)
$.ajax({
type: "POST",
url: "result.php",
data: data,
success: function(hasil) {
$('.response_div').html(hasil);
}
})
});

JavaScript Timer pauses on page reload

I am using a JavaScript code for a timer which works fine with the code below, the only problem is when i refresh the page one second loses.
I need the timer to keep running even if i refresh the page.
I tried to get local time setHours(00) nothing changed.
How do I keep timer running ?
function work(x, id, id_p) {
var span = document.getElementsByClassName('data-work');
for (i = 0; i < span.length; i++) {
var totalsum = span[i].dataset.totalwork;
}
var Clock = {
totalSeconds: parseInt(x),
totalSecondsproject: parseInt(totalsum),
start: function () {
var self = this;
function pad(val) {
return val > 9 ? val : "0" + val;
}
this.interval = setInterval(function () {
self.totalSeconds += 1;
self.totalSecondsproject += 1;
var hour = pad(Math.floor(self.totalSecondsproject / 3600));
var min = pad(Math.floor(self.totalSecondsproject / 60 % 60));
var sec = pad(parseInt(self.totalSecondsproject % 60));
var totat_work = hour + ":" + min + ":" + sec;
var totat_work_db = self.totalSeconds;
$(".totatl_hour_work").text(totat_work);
$.ajax({
type: 'Post',
url: 'includes/function.php',
data: {divVal: totat_work_db, id_interview: id, id_project:id_p}
});
}, 1000);
}
};
$('.startButton').ready(function () {
Clock.start();
var refresh = setInterval(function () {
$(window).attr('location', 'agent_dashboard.php?autorefresh');
}, 300 * 1000);
});
}

Ajax Chrome wont evaluate script immediately in success

I have this source:
$("#allDataForm").submit( function (e) {
e.stopPropagation();
var formData = $("#allDataForm").serialize();
var count = formData.substring(formData.indexOf('&count=')+7,formData.indexOf('&x='));
var x = parseInt(formData.substring(formData.indexOf('&x=')+3, formData.length));
if (formData.indexOf('=description&') > 0 &&
formData.indexOf('=name&') > 0 &&
formData.indexOf('=identifier&') > 0) {
var head = 0;
if (formData.indexOf('firstashead=on') > 0) {
head=1;
}
head = parseInt(head);
var imported = 0;
var updated = 0;
$("#assignTable").hide();
$("#send").hide();
$("#status").show();
var totalTime = 0;
if (count > 0) {
for (s=x; s<=count; s++) {
var startms = new Date().getTime();
$.ajax({
type: "POST",
data: formData,
dataType: "html",
url: "/import/universalimport/",
async: false,
success: function(msg, textStatus, XMLHttpRequest) {
console.log($.makeArray(arguments), 'success');
console.log(textStatus, 'success1');
console.log(XMLHttpRequest, 'success2');
if (msg == 'imported') {
imported = parseInt(imported)+1;
} else if (msg == 'updated') {
updated = parseInt(updated)+1;
}
var endms = new Date().getTime();
totalTime = totalTime + (endms-startms);
x = totalTime / 1000;
tSeconds = Math.abs((x % 60).toFixed(0));
if (tSeconds < 10) {
tSeconds = 0+String(tSeconds);
}
x /= 60;
tMinutes = Math.abs((x % 60).toFixed(0));
if (tMinutes < 10) {
tMinutes = 0+String(tMinutes);
}
x /= 60;
tHours = Math.abs((x % 24).toFixed(0));
if (tHours < 10) {
tHours = 0+String(tHours);
}
x = (totalTime*(count-s-head)/s) / 1000;
aSeconds = Math.abs((x % 60).toFixed(0));
if (aSeconds < 10) {
aSeconds = 0+String(aSeconds);
}
x /= 60;
aMinutes = Math.abs((x % 60).toFixed(0));
if (aMinutes < 10) {
aMinutes = 0+String(aMinutes);
}
x /= 60;
aHours = Math.abs((x % 24).toFixed(0));
if (aHours < 10) {
aHours = 0+String(aHours);
}
eval($("#bar").css('width', (parseInt(s)/parseInt(count)*100).toFixed(2) + '%'));
$("#bar").html((parseInt(s)/parseInt(count)*100).toFixed(2) + '%');
$("#imported").html(imported);
$("#updated").html(updated);
$("#summary").html(imported+updated);
$("#count").html(count-head);
$("#elapsed").html(tHours + ':' + tMinutes + ':' + tSeconds);
$("#remaining").html(aHours + ':' + aMinutes + ':' + aSeconds);
formData = formData.substring(0, formData.indexOf('&x=')+3) + parseInt(s);
}
});
}
}
} else {
alert('Pro provedení importu je nutno napárovat minimálně Název, Popis a Identifikátor!');
}
return false;
});
In Google Chrome it wont evaluate script inside success immediately but after all ajax calls it execute the last one. When I add alert() inside success it works fine and in Firefox it works well.
Async is a depreciated feature. Success is also on its way out. You should be using
$.ajax({
type: "POST",
data: formData,
dataType: "html",
url: "/import/universalimport/"
}).done(msg, textStatus, XMLHttpRequest) {
... rest of code when done here
Here is a jsfiddle showing a set of $.ajax() POSTs being sent all at once and coming back at different intervals:
<ul id='log'></ul>
<script>
var call,
log = $('#log');
for (call = 0; call < 10; call++) {
$.ajax({
type: 'POST',
url: '/echo/html/',
data: {
html: "ajax response #" + call,
delay: 3
},
success: function(data) {
log.append('<li>'+data+'</li>')
console.log(data);
},
dataType: 'html'
});
log.append('<li>'+('ajax request #' + call)+'</li>')
console.log('ajax request #' + call);
}
</script>
I've run this in Chrome and Firefox and the behavior appears to be the same (the ajax responses return out of order as though they had been submitted at different intervals). Does this model the problem you are talking about?
Solved by recursive calling asynchronous ajax. Thanks for help.

Categories

Resources