How do I make a Ajax call only once? - javascript

I have the following code that fires when a user scrolls to the bottom of the screen. The only issue is that I would like for the Ajax call to fire only once. My code is:
var w = $(window);
window.onscroll = function(ev) {
if ($(document).height() - w.height() == w.scrollTop()) {
$('#loading-image').show();
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
}
});
}
};

The simplest way you can add a global variable and check it this way:
var w = $(window);
var BOTTOM_REACHED = false;
window.onscroll = function(ev) {
if ($(document).height() - w.height() == w.scrollTop() && !BOTTOM_REACHED) {
BOTTOM_REACHED = true;
$('#loading-image').show();
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
BOTTOM_REACHED = false;
}
});
}
};

You can try like this :
var bottom_reached = false;
$(window).scroll(function(){
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
bottom_reached = true;
$('#loading-image').show();
if(bottom_reached)
{
bottom_reached = false;
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
}
});
}
}
});

Related

$(window).scroll(function () { stopping ajax from firing

For some reason the $(window).scroll(function () { is stopping ajax from firing.
I've done a few tests. I completely removed my CSS fileto remove any overflows or heights set in the html,body, as this was a common thing that was stopping it on the net.
when I remove just the line $(window).scroll(function () {my ajax fires on page load but then if I want to scroll for new content i can't.
$(document).ready(function() {
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
flag = true;
first = $('#first').val();
limit = $('#limit').val();
no_data = true;
if (flag && no_data) {
flag = false;
$('#loadmoreajaxloader').show();
$.ajax({
url: "commentedoncontent.php",
dataType: "json",
method: "POST",
cache: false,
data: {
start: first,
limit: limit
},
success: function(data) {
flag = true;
$('#loadmoreajaxloader').hide();
if (data.count > 0) {
first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val(first + limit);
$.each(data.posts, function(i, response) {
//post content here
});
} else {
alert('No more data to show');
no_data = false;
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
flag = true;
no_data = false;
}
});
}
}
});
});

Script is working fine with IE but not with Chrome? mvc.net

This is a script :
<script type="text/javascript">
var pageSize = 10;
var pageIndex = 0;
$(document).ready(function () {
GetData();
$(window).scroll(function () {
if ($(window).scrollTop() ==
$(document).height() - $(window).height()) {
GetData();
}
});
});
function GetData() {
$.ajax({
type: 'GET',
url: '/home/GetData',
data:{"pageindex":pageIndex,"pagesize":pageSize},
dataType: 'json',
success: function (data) {
if (data != null) {
for (var i = 0; i < data.length; i++) {
$("#container").append("<h2>" +
data[i].CompanyName + "</h2>");
}
pageIndex++;
}
},
beforeSend : function () {
$("#progress").show();
},
complete : function () {
$("#progress").hide();
},
error: function () {
alert("Error while retrieving data!");
}
});
}
I have tried removing the type="text/javascript". What might be the possible issue, and how to fix scripting issues on diff browsers.
How can I use this script in case of tight coupling like, DisplayFor(x => x.name) in mvc .net?

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

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