Jquery ajax is calling multiple time on scroll - javascript

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

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 stop function from another function then start it again with another parameter

i am trying to make a slider, i have function that getting array of objects and loop it, and i have select that change models list, but when i change select, old instance of function still work, they are starting to work together. So i add function stopper, but it wont work. Help please, thank you!
var keepGoing = true;
function slideList(models) {
$.each(models, function (index, model) {
setTimeout(function () {
if (keepGoing != false) {
moditem.innerHTML = "";
modlist.value = model.id;
var photo = document.createElement('IMG');
photo.src = model.photos[0].file;
photo.classList.add('img');
moditem.appendChild(photo);
if (index >= models.length - 1) {
slideList(models);
}
} else {
return false;
}
},
5000 * index);
});
}
function startLoop() {
keepGoing = true;
}
function stopLoop() {
keepGoing = false;
}
$("#car-type-select").on('change', function () {
stopLoop();
getModels(this.value);
});
Clear timeout:
var timer;
function slideList(models) {
$.each(models, function (index, model) {
timer = setTimeout(function () {
moditem.innerHTML = "";
modlist.value = model.id;
var photo = document.createElement('IMG');
photo.src = model.photos[0].file;
photo.classList.add('img');
moditem.appendChild(photo);
if (index >= models.length - 1) {
slideList(models);
}
},
5000 * index);
});
}
$("#car-type-select").on('change', function () {
clearTimeout(timer);
getModels(this.value);
});
Other unimportant functions
function getModels(cartype_id) {
$.ajax({
type: 'POST',
url: '/home/models/get',
data: {
'cartype_id': cartype_id
},
success: function (models) {
makeList(models);
slideList(models)
}
});
}
function makeList(models) {
modlist.innerHTML = "";
$.each(models, function (index, model) {
var option = document.createElement("option");
option.text = model.manufacturer.name + ' ' + model.name;
option.value = model.id;
modlist.add(option);
});
}
You need to use clearTimeout to stop function in setTimout to stop executing.
Example:
var timer = setTimeout(function(){ /* code here */ }, 3000)
clearTimeout(timer) //it will stop setTimeout function from executing.
After looking at code update:
Can you please try:
var timers = [];
function slideList(models) {
$.each(models, function(index, model) {
timers.push(setTimeout(function() {
moditem.innerHTML = "";
modlist.value = model.id;
var photo = document.createElement('IMG');
photo.src = model.photos[0].file;
photo.classList.add('img');
moditem.appendChild(photo);
if (index >= models.length - 1) {
slideList(models);
}
},
5000 * index));
});
}
$("#car-type-select").on('change', function() {
$.each(timers, function(i, timer) {
clearTimeout(timer);
})
getModels(this.value);
});
setTimeout is getting called in loop to need array of setTimeout references

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

jquery load more onscroll calling the function many times at once

I have written an javascript which load more when user scroll to bottom of a div .
This is the code I'm using :
var loadingSet = 0
var diMore = 1
var ob = 'default';
var db = 'desc' //نزولی
var doAppend = true
var loading= false;
function sort(){
diMore=1
ob = $('#ob').val();
db = $('#db').val();
loadingSet=-1
doAppend = false
loadMore()
}
function loadMore()
{
if (diMore ==1 && !loading){
var loading= false;
loadingSet++ ;
loading=true
$(document).ready(function() {
$(document).on({
ajaxStart: function() { $("#spinner").css("display", "block"); },
ajaxStop: function() { $("#spinner").fadeOut('slow'); }
});
$.ajax({
type: "POST",
url:baseUrl+ "getNewItems.php",
data: "limit=<?php echo $limit?>&stId=<?php echo $admins_id?>&status="+status+"&ob=" + ob +"&da="+ db +"&loadingSet="+loadingSet+"&submit=true",
success: function(msg){
str=$.trim(msg)
var More = str.split('##');
if (More[0] == 'n'){
diMore=0
}else{
$(window).bind('scroll', bindScroll2);
loading=false
}
if (doAppend){
$('#prodDiv').append(More[1])
}else{
doAppend=true
$('#prodDiv').html('')
$('#prodDiv').fadeOut(500, function() {
$(this).html(More[1]).fadeIn(500);
});
}
}
})
})
}
}
function bindScroll2(){
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#mainDivCategory').offset().top + $('#mainDivCategory').outerHeight() - window.innerHeight) {
$(window).unbind('scroll');
if (!loading){
loadMore();
}
}
});
}
$(window).scroll(bindScroll2);
The problem is that when I scroll at the bottom of the div , the loadMore function is calling so many time at one . maybe about 50 -60 request at once.
What's the problem ?
Thanks

JQuery: How to refactor JQuery interaction with interface?

The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )

Categories

Resources