JavaScript Increment number every time (if statement) is true - javascript

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

Related

set and clear interval by ajax

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

<video> doesn't call ended event

How to detect if context window of iframe has a video on the page?
window.onload = function () {
var pages = '#ViewBag.pages';
var p = JSON.parse(pages.replace(/(&quot\;)/g, "\""));
var i = 0;
var mi = p.length - 1;
var interval;
console.log("frame is loaded");
var video = $(document).find("iframe").contents().find("video");
if (video.length == 1) {
console.log(0);
clearInterval(interval);
video.on('ended', function () {
document.getElementById('slider').src = src;
});
}
else { console.log(5);
interval = setInterval(function () {
i++;
if (i > mi) { i = 0 }
var src = p[i];
$.ajax({
async: false,
url: src,
type: 'GET',
success: function () {
document.getElementById('slider').src = src;
}
});
}, 5000);
}
}
Can anyone tell me what's wrong and why the page with video loops again and again without 'onended' event?
If you are using HTML5.
Here is an example -
$(document).ready(function(){
var videos = $(document).find("iframe").contents().find("video");
$(videos).each(function(){
$(this).on('ended', function(){
console.log('Video has ended!');
// Execute you function to move next slides
});
});
});

async and set timeout

I am having some problem using the settimeout() in my function. I am new to async. No matter how much I try I just can't make the timeout work. My code works perfect so that is not the problem. I need the request to execute every 10 seconds. Thanks for the help.
function getContent() {
function getPelicula(pelicula, donePelicula) {
var peli = pelicula.title;
//request id
request({
url: "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false",
method: "GET",
json: true,
}, function(error, res, body) {
if (error) {
console.error('Error getPelicula: ', error);
return;
}
var control = body.results.length;
if (control > 0) {
var year_base = pelicula.launch_year;
var id = body.results[0].id;
var year = body.results[0].release_date;
var d = new Date(year);
var year_solo = d.getFullYear();
if (year_base == year_solo) {
pelicula.id = id;
pelicula.year_pagina = year_solo;
}
} else {
pelicula.id = null;
pelicula.year_pagina = null;
}
donePelicula();
});
}
}
To do something in a loop, use setInterval.
UPD:
In general, there're two ways of executing some code in loop
1 setTimeout :
var someTimer = setTimeout(function sayHello(){
console.log("hello!");
someTimer = setTimeout(sayHello, 2000);
}, 2000);
Notice that someTimer variable is needed to stop the looping process if you need: clearTimeout(someTimer)
2 setInterval:
var someIntervalTimer = setInterval(function(){
console.log("I'm triggered by setInterval function!");
}, 2000);
Invoke clearInterval(someIntervalTimer) to stop the looping
Both functions are treated as properties of the global Window variable. By default, the following code works:
var window = this;
console.log("type of setTimeout: " + typeof window.setTimeout);
console.log("type of setInterval: " + typeof window.setInterval);
Try putting it in another function so:
domore(pelicula,donePelicula);
function domore(pelicula,donePelicula) {
// 1 second
var timeout = 1000;
for (var i = 1; i < pelicula.length; i++) {
createData(pelicula[i],donePelicula,timeout);
timeout = timeout + 800;
}
}
function createData(peli,donePelicula,timeout) {
setTimeout(function() { getData(peli,donePelicula); }, timeout);
}
function getData(peli,donePelicula) {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
domore(allText,donePelicula);
}
}
}
txtFile.send(null);
}

How to make my ajax polling run for 5 times only then terminate

I want to do is do now is instead of infinite ajax polling i want to do is make it run for 5 times then terminate the ajax infinite polling.
My problem is it doesn't work as i wanted. Can anyone help me with this?
ajax script:
$(document).ready(function () {
var = x;
var countTimer = setInterval(function () {
if(x++ === 5){
clearInterval(countTimer);
}else{
codeValue()
}
}, 500)
function codeValue() {
$.ajax({
type: "POST",
url: 'codeTime.php',
dataType: "JSON",
cache: false,
success: function (result) {
$("#count").val(result.user_code);
}
});
return false;
}
});
Change to var x = 0
I'd personally do it like this:
var x = 0;
var countTimer = setInterval(function () {
if(x === 5){
clearInterval(countTimer);
}else{
codeValue();
x++;
}
}, 500);
First of all you do not define x, u have var = x; which should be a syntax error. Try this:
$(document).ready(function () {
var countTimes = 0;
var numberOfTimes = 5;
var countTimer = 0;
countTimer = setInterval(function () {
countTimes++;
if(countTimes > numberOfTimes){
clearInterval(countTimer);
}else{
codeValue();
}
}, 500);
function codeValue() {
$.ajax({
type: "POST",
url: 'codeTime.php',
dataType: "JSON",
cache: false,
success: function (result) {
$("#count").val(result.user_code);
}
});
return false;
}
});

Jquery ajax is calling multiple time on scroll

Here in the below code iam calling ajax on scroll.
But this is calling ajax multiple times. To restrict this i added setTimeout function and flag (i.e. isActive) still it is calling two times.
Please help me where iam going wrong.
Thanks in advance
var isActive = false;
var sIndex =12;
var myflag = '1';
var offSet = 12;
var timeout;
jQuery(window).scroll(function () {
if(typeof timeout == "number") {
window.clearTimeout(timeout);
delete timeout;
}
timeout = window.setTimeout( check, 500);
});
function check(){
var cat = $(".mi-selected").attr('id');
var tecID = $("#technologyID").val();
var notSameInd = $("#notSameInd").val();
var sIndex =$("#startInd").val();
if (!isActive && ($(window).scrollTop() + $(window).height() == $(document).height()) && (sIndex !== notSameInd) ) {
var isActive = true;
jQuery.ajax({
type: "POST",
url: 'http://some.com/responcePortfolio.php',
data: {
tecID:tecID,
cat:cat,
startIndex:sIndex,
offset:offSet,
count_now:count_now
},
success: function (result) {
if(result !== ''){
jQuery("#LoaderImage").hide();
jQuery("#portfolioList").append(result);
$("#notSameInd").val(sIndex);
sIndex = parseInt(sIndex) + parseInt(offSet);
$("#startInd").val(sIndex);
}
else{
jQuery("#LoaderImage").hide();
}
isActive = false;
},
error: function (error) {
//alert(error);
}
});
}
}

Categories

Resources