I have this script which makes ajax request when user reaches the end of the page. It is based on scroll event. At page load I am showing only 16 products on the user screen and when he scrolls down I wish to load another 16 products. My script is working but it executes more than one ajax request which is not what I want. The idea is just to show another set of 16 products. The script is:
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {
//here I count how many products I have shown already
var productsshown = $(".productcell").length;
$('.made').hide();
$.ajax({
type: "post",
url: "./ajax/get_more_products.php",
data: {
"product": productsshown
},
dataType: 'json',
cache: false,
success: function(data) {
$("#bcontent").html(data);
$('.made').show();
}
});
}
});
As you can see I have a div which I am using as controler and when user see this div - the ajax is being executed. The result from ajax is being loaed into another div with id="content"
How to avoid scroll event to execute the ajax call more than once? I tried by hiding my controller div .made and upon ajax responce I am showing it again so it can be executed for another 16 products when user goes down to it again.. but ajax is always called executed more than once as I want it..
hmm, Here is a small addition to your code, adding a flag swiched whenever you load more items:
var _itemsLoading = false;
if ((!_itemsLoading) && ($(window).scrollTop() + $(window).height() > $('.made').offset().top)) {
//here I count how many products I have shown already
var productsshown = $(".productcell").length;
$('.made').hide();
_itemsLoading = true;
$.ajax({
type: "post",
url: "./ajax/get_more_products.php",
data: {
"product": productsshown
},
dataType: 'json',
cache: false,
success: function(data) {
$("#bcontent").html(data);
$('.made').show();
_itemsLoading = false;
}
});
}
Simple store the timestamp then you fire your ajax request and reset it then it returns or after 2 seconds.... then the timestamp is set don't fire your requests.
I don't handle the scroll event. I use setInterval() and I test if the position has changed since previous tic.
I just replaced
if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {
with:
if($(window).scrollTop() + $(window).height() == $(document).height()){
and used the page bottom as ajax controller.. It works now, thanks !
Related
Hello I'm working on a website with a color slider that append a specific color page to the DOM after a slide change. I want people to still be able to go through the different slide pretty quickly and load the ajax page only if the user didn't change the slide for a specific time (for example 1000ms).
I tried setInterval, setTimeout and the ajax timeout parameter but it isn't working, it just adds requests to the call stack and after the timeout duration it appends the div 5 times.
Here's the ajax call:
$.ajax({
url: "/wp-admin/admin-ajax.php",
type:"POST",
data: {
action: "my_custom_color",
post_link: post_ID
}, success: function (response) {
$('.color').prepend(response);
},
})
I want to be able to do something like this:
colorsMonoSlider.events.on('indexChanged', () => {
setTimeout(() => {
customizedFunction()
}, 1000);
});
But without filling the call stack (maybe emptying it at each call), the ajax request should only trigger once after the timeout, I can't disable the slider navigation or use async: false because as I said users need to be able to spam click to go through the slider fast.
Any tips welcome, thanks in advance.
You need to cancel both your ajax call and timer functions before invoking again.
Assuming the customized function has the ajax call.
var xhr,timer;
function customizedFunction(){
xhr && xhr.abort();
xhr = $.ajax({
url: "/wp-admin/admin-ajax.php",
type:"POST",
data: {
action: "my_custom_color",
post_link: post_ID
}, success: function (response) {
$('.color').prepend(response);
},
})
}
colorsMonoSlider.events.on('indexChanged', () => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
customizedFunction()
}, 1000);
});
I am populating table data with PHP and JQUERY
The problem is that the scroll function is not firing off. I do not have any errors.
I thought maybe I did not load Jquery in the page correctly so I did,
alert( "This means you have JQUERY" );
The alert function did fire off. This is a wordpress site I am working with a plugin and a template file that I wrote.
Is there any reason why the scroll effect might not work? I have never used this before. Could I possible need to load additional libraries or something of that nature?
$(document).ready(function(){
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#productResults").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if($(document).height() <= $(window).scrollTop() + $(window).height()) {
if($(".pagenum:last").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum:last").val()) + 1;
alert.function('Hey the scroll effect works.');
getresult('../wuno-search/inventory-search.php?page='+pagenum);
}
}
});
});
Also I am confused exactly how to add PHP to this function
getresult('../wuno-search/inventory-search.php?page='+pagenum);
For example if I wanted to change the url path to a variable like this,
getresult('<?php echo $assetPath ?> ?page='+pagenum);
Is that correct?
I have a page that makes different ajax calls based on what element one clicks on. There are four IDs and only one should be visible at any given moment. My problem comes when I load new ajax content into a div - I get a flash for a very brief second of the previous content. Here is one of my functions for one of the calls (they are all essentially the same). At the beginning of the function I hide everything. Then after the ajax has loaded I show the relevant div. I'm confused about why this would not work. There should be no flash, since all the div are hidden, right?
$('body').on("click", "#answer-submit", function() {
$('#games, #location, #question, #answer').css('display' , 'none');
var theAnswer = $('#challenge-answer').val();
$.ajax({
type: "POST",
url: "ajax/answer.php",
data: { answer : theAnswer },
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0) {
$('#answer').html(msg);
}
}
});
$('#answer').css('display' , 'block');
});
The problem is an asynchronous request is going to happen asynchronously. In other words, your success function is going to be called after $('#answer').css('display' , 'block'); (it is a race condition but it's practically guaranteed). The solution is simple -- move $('#answer').css('display' , 'block'); into the success function:
$('body').on("click", "#answer-submit", function() {
$('#games, #location, #question, #answer').css('display' , 'none');
var theAnswer = $('#challenge-answer').val();
$.ajax({
type: "POST",
url: "ajax/answer.php",
data: { answer : theAnswer },
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0) {
$('#answer').html(msg);
$('#answer').css('display' , 'block');
}
}
});
});
You can even chain it like so:
if (parseInt(msg) != 0) {
$('#answer')
.html(msg)
.css('display', 'block');
}
I have a div call load-ajax-hotels in which I am trying to load php files after the click event has been fired.
Say that I am trying to load alpha.php, beta.php, gamma.php ... delta.php
$("span.dessert-make").click(function(){
/* Load Initial Data */
$(".ajax-load-hotels").load("./php/alpha.php");
$.get("./php/beta.php", function(data){
$(".ajax-load-hotels").append(data);
});
$.get("./php/gamma.php", function(data){
$('.ajax-load-hotels').append(data);
});
$.get("./php/delta.php", function(data){
$('.ajax-load-hotels').append(data);
});
});
But this call is not working properly. I mean that at each instance of the click event I get different results. Some times just alpha.php and beta.php gets displayed some times every php files duplicate comes along. Its random every time. Can some one tell me what the problem is?
And also how do I make php files load as the user scrolls down to bottom of the page. How to implement the scrollTo() method for this. x and y pos becomes different once window resizes.
Sorry. That I might have overlooked. I corrected it.
Assuming you are trying to load these sequentially (syncronously), I would probably go with something like this:
function load_pages(index, pages) {
$.get("./php/" + pages[index] + ".php", function(data) {
$(".ajax-load-hotels").append(data);
if (index + 1 < pages.length) {
load_pages(index + 1, pages);
}
})
}
$("span.dessert-make").click(function(){
load_pages(0, ["alpha", "gamma", "delta"]);
});
You missed a }) at
$.get("./php/2.php", function(data){
$(".ajax-load-hotels").append(data); // here is missed });
$.get("./php/3.php", function(data){
$('.ajax-load-hotels').append(data);
});
Correct:
$.get("./php/2.php", function(data){
$(".ajax-load-hotels").append(data);
});
$.get("./php/3.php", function(data){
$('.ajax-load-hotels').append(data);
});
EDIT 1:
And, $.get is asynchronous.
To make it synchronous (I provided just an example):
$.ajax({
url: urltophp,
async: false,
success: function(data) { $(".ajax-load-hotels").append(data) },
dataType: 'html'
});
I have a nifty little piece of Ajax code that loads in PHP.
http://www.moneyworrier.com/client-stories/
What happens is that when you click on a menu item on the left-hand navigation, it reloads a Div with content appropriate.
What it does however is loop through previous requests, which is bothersome (Click on any left hand item 3x and you will see what I mean). I think I need to find a function that does the equivalent of exit; and clears any post data.
My call in code is:
Video
And my JS looks like:
$(document).ready(function () {
$('a.media').click(function () {
var usr = $(this).attr('rel');
$("#displaystories").html('Retrieving..');
$.ajax({
type: "POST",
url: "/client-stories/media.php",
data: "showcode=" + usr,
success: function (msg) {
$("#displaystories").ajaxComplete(function (event, request, settings) {
$(this).html(msg);
});
}
});
});
});
You're binding a new listener to ajaxComplete on every click. Your success callback should just be:
success: function(msg) {
$("#displaystories").html(msg);
}