Get More Table Data On Page Scroll AJAX - javascript

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?

Related

What is the proper way of doing long polling using jQuery and AJAX

I have a project which involves live notification. So I stumbled upon using socket io but I didn't have enough time to learn it yet. So I tried doing it with AJAX and jQuery. Below is my code structure and I was wondering if this is gonna work with no drawbacks?
setInterval(function(){
if( !element.hasClass('processing') ){
element.addClass('processing');
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {},
success: function( response ){
/* Success! */
element.removeClass('processing');
}
});
}
}, 2500);
Some Extra Info
The way you described will work. From Experience I would just like to point out some things.
I usually do a recursive function, allows you to wait your interval between ajax calls and not a fixed rate. //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM.
Use window.setTimeout() with an isActive flag. //ALLOWS YOU TO STOP POLLING FOR WHATEVER REASON, AND BECAUSE FUNCTION IS RECURSIVE START UP AGAIN IF NEED BE
For Sake of being thorough, I found it is always a good idea to handle the error case of the $.ajax() post. You could perhaps display some message telling the user he is no longer connected to the internet etc.
Some Sample Code:
var isActive = true;
$().ready(function () {
//EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
//IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
pollServer();
});
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "...",
type: "POST",
success: function (result) {
//SUCCESS LOGIC
pollServer();
},
error: function () {
//ERROR HANDLING
pollServer();
}});
}, 2500);
}
}
NOTE
This is just some things I picked up using the exact method you are using, It seems that Web Sockets could be the better option and I will be diving into that in the near future.
Please refer :
Jquery : Ajax : How can I show loading dialog before start and close after close?
I hope this could help you
$("div.add_post a").click(function(){
var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
dlg.dialog("show");
$.ajax({
url : "/add.php",
complete : function (){
dlg.dialog("hide");
}
});
return false;
});
//--Loading dialog
function loadingDialog(dOpts, text = "пожалуйста подождите, идет загрузка...")
{
var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt='загрузка'/> "+text+"<div>").dialog(dOpts);
$(".ui-dialog-titlebar").hide();
return dialog;
}

Execute ajax when html element visible on user screen

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 !

AJAX, PHP, MySQL. (refreshing tables without blink)

I can't find a solution for this and I can't believe I can't find just one example!
Ok, I have a kind of monitory (PHP / MySQL), refreshed by Javascript. The thing is, that my script reload an entire php page, where I have the MySQL Querys. So, every reload I see a little blink, which is nothing else that the page loading.
This is what I have:
(function($) {
$(document).ready(function() {
$.ajaxSetup( {
cache: false,
beforeSend: function() {
$('#colas').hide();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
$('#colas').show();
},
success: function() {
$('#loading').hide();
$('#colas').show();
}
});
var $colas = $("#colas");
$colas.load("panelColasRealtime.php");
var refreshId = setInterval(function() {
$colas.load('panelColasRealtime.php');
}, 8000);
});
})(jQuery);
I load "panelColasRealtime.php" right here:
<div id="colas"></div>
This is working, but I don't want this solution, I don't like that blink. I want to refresh the monitory without reload the php page, just the data.
I think that AJAX is my best choice, but I can't find any example.
Summarizing:
I would like a realtime monitory (every X secods) of my BD and show it .
If anyone has an example script I would really appreciated it.
if you just want to refresh the data here is a simple example which refreshes every 5 seconds
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({
type: "GET",
url: "data_source_page.php",
dataType: "html",
success: function(response) {
$(".refresh").html(response);
setTimeout(loadData, 5000);
}
});
};
html
<div class="refresh"></div>

Jquery get() method working in random

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

jQuery AJAX triggering too quickly

I have a relatively simple jQuery AJAX call wrapped in a function and I am testing my error functionality. The problem I am facing is the AJAX call happens too quickly! It is causing my 'H6' and '.loading' elements to start repeating. The behaviour I require is to remove the elements, then call the ajax.
function getAvailability(form) {
var str = $(form).serialize(),
warning = $('#content h6');
if ( warning.length > 0 ) {
$(warning).remove();
$('<div class="loading">Loading…</div>').insertAfter(form);
}
else
{
$('<div class="loading">Loading…</div>').insertAfter(form);
}
$.ajax({
type: "POST",
url: "someFile",
data: str,
success: function(calendar) {
$('.loading').fadeOut(function() {
$(this).remove();
$(calendar).insertAfter(form).hide().fadeIn();
});
},
error: function() {
$('.loading').fadeOut(function() {
$('<h6>Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
});
}
});
return false;
}
I would love to sequence it like so -> Remove 'warning' from page, add .loading. Then trigger AJAX. Then fade out .loading, add & fade in warning/calendar dependent on success.
I have amended my original code, and I have got the function to behave as expected, primarily because I have disabled the submit button during the ajax process.
function getAvailability(form) {
var str = $(form).serialize(),
btn = $('#property_availability');
// Disable submit btn, remove original 'warning', add loading spinner
btn.attr("disabled", "true");
$('.warning').remove();
$('<div class="loading">Loading…</div>').insertAfter(form);
$.ajax({
type: "POST",
url: "public/ajax/returnAvailability1.php",
data: str,
success: function(calendar) {
$('.loading').fadeOut(function() {
$(this).remove();
$(calendar).insertAfter(form).hide().fadeIn();
});
},
error: function() {
$('.loading').fadeOut(function() {
$(this).remove();
$('<h6 class="warning">Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
btn.removeAttr("disabled");
});
}
});
return false;
}
I believe that the original sequence was not working as expected due to the time delay created by the fadeOut() functions.
Instead of adding and removing warning, why not just show/hide leveraging ajaxStart and ajaxStop?
warning.ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).fadeOut();
});
If you need to sequence your events, then you should try using the deferred and promise methods that are a part of the jQuery.ajax API. This article does a good job of introducing them: http://www.bitstorm.org/weblog/2012-1/Deferred_and_promise_in_jQuery.html

Categories