I am fetching data from db when i scroll the page. The code works fine on desktop browsers but not on mobile browsers.
I have tried different solutions from different post but all in vain.
$(document).ready(function(){
$('body').on('touchmove', onScroll);
$(window).on('scroll', onScroll);
function onScroll(){
var lastID = $('.load-more').attr('lastID');
if(($(window).scrollTop() + window.innerHeight >= document.body.scrollHeight) && (lastID != 0)){
$.ajax({
type:'POST',
url:'getData.php',
data:'Slno='+lastID,
beforeSend:function(){
$('.load-more').show();
},
success:function(html){
$('.load-more').remove();
$('#postList').append(html);
}
});
}
};
});
Try this code :
$(document).ready(function(){
$('body').on('touchmove', onScroll);
$(window).on('scroll', onScroll);
function onScroll(){
var lastID = $('.load-more').attr('lastID');
if ($(window).scrollTop() > $(document).height() - $(window).height() - 100 && (lastID != 0)) {
$.ajax({
type:'POST',
url:'getData.php',
data:'Slno='+lastID,
beforeSend:function(){
$('.load-more').show();
},
success:function(html){
$('.load-more').remove();
$('#postList').append(html);
}
});
}
};
});
Related
I am making on scroll data load from mysql table using below code but on scroll it repeat some of data while loader running
$(document).ready(function(){
$(window).scroll(function(){
var lastID = $('.load-more').attr('lastID');
if(($(window).scrollTop() == $(document).height() - $(window).height()) && (lastID != 0)){
$.ajax({
type:'POST',
url:'result_data.php',
data:'id='+lastID,
beforeSend:function(){
$('.load-more').show();
},
success:function(response){
setTimeout(function() {
$('.load-more').remove();
$('#postList').append(response);
}, 400);
}
});
}
});
});
You can use .after() or .insertAfter()
The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after(), the content to be inserted comes from the method's argument: $(target).after(contentToBeInserted). With .insertAfter(), on the other hand, the content precedes the method and is inserted after the target, which in turn is passed as the .insertAfter() method's argument: $(contentToBeInserted).insertAfter(target).
$(document).ready(function(){
$(window).scroll(function(){
var lastID = $('.load-more').attr('lastID');
if(($(window).scrollTop() == $(document).height() - $(window).height()) && (lastID != 0)){
$.ajax({
type:'POST',
url:'result_data.php',
data:'id='+lastID,
beforeSend:function(){
$('.load-more').show();
},
success:function(response){
setTimeout(function() {
$('.load-more').remove();
// $('#postList').append(response);
$('#postList').after(response);
}, 400);
}
});
}
});
});
UPDATE 2 18.05.2020
(AJAX) URL pagination on refresh + window.history.replaceState + window.history.pushState +location.pathname
After refresh Test3
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$('#load_data').html('<div id="status" style="" ></div>');
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
success:function(data){
$('#load_data').html(data);
}
});
}
$(document).on('click', '.pagination_link', function(event)
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
//Now push PAGE to URL
window.history.pushState({page}, `Selected: ${page}`, `${ 'page=' + page}`)
//window.history.pushState({page}, `Selected: ${page}`, `./selected=${page}`)
return event.preventDefault();
});
window.addEventListener('popstate', e => {
var page = $(this).attr("id");
load_data(e.state.page);
console.log('popstate error!');
});
//history.replaceState({page: null}, 'Default state', './');
var params = new URLSearchParams(location.search);
params.set('page');
window.history.replaceState({}, "", decodeURIComponent(`${location.pathname}?${params}`));
});
I've built a PHP AJAX pagination that works -> ajax pagination.
I'm new to jQuery/ajax. I am not able to understand the usage the url parameter.
My output: pagination2.php
I want the output: pagination2.php/page=2,3,4....
Any ideas?
My code index.php
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$('#load_data').html('<div id="status" style="" ></div>');
var action = 'pagination2';
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
complete: function(){
alert(this.url)
},
success: function(data){
$('#load_data').html(data);
},
})
}
$(document).on('click', '.pagination_link', function(event)
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
return event.preventDefault();
});
});
pagination2.php
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
UPDATE1
I added: history.pushState but I don't know if this method is correct. I can manipulate next - back /selected=2, selected=3... But, another problem arises, after refresh selected disappears. Test 2
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$('#load_data').html('<div id="status" style="" ></div>');
var action = 'pagination2';
$.ajax({
url:"pagination2.php",
method:"POST",
error: function(xhr, text){
alert("Whoops! The request for new content failed");
},
data:{page:page},
success:function(data){
$('#load_data').html(data);
},
})
}
$(document).on('click', '.pagination_link', function(event) pagination
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
history.pushState({page}, `Selected: ${page}`, `./selected=${page}`)
return event.preventDefault();
});
window.addEventListener('popstate', e => {
var page = $(this).attr("id");
load_data(e.state.page);
console.log('popstate error!');
});
history.replaceState({page: null}, 'Default state', './');
});
When I use this code then multiple time ajax call 4-5 time load same data in output. Please help me to solve this. Please see the flowing code.
<script>
$(document).ready(function () {
$(window).scroll(function () {
if ($(document).height() - 50 <= $(window).scrollTop() + $(window).height()) {
sendData();
}
});
function sendData() {
var offset_val = $('#offset_val').val();
$.ajax({
url: '',
type: 'POST',
data: {offset_val: offset_val},
dataType: "json",
success: function (response) {
if (response.status) {
$('#load_data').append(response.all_data);
$('#offset_val').val(response.offsets);
setTimeout(function () {
//$('.animation_image').hide();
}, 600);
} else {
$('#no-data-found').html(response.all_data);
// $('.animation_image').hide();
}
}
});
}
});
</script>
That's not the ajax issue, check the following line:
$(window).scroll(function () {
if ($(document).height() - 50 <= $(window).scrollTop() + $(window).height()) {
sendData();
}
});
The above code executes for each single scroll moment when condition return true. That's why it is initiating multiple request for a single scroll.
What is the best way to display or deal with a large result on success while waiting for PHPto render that result. I would like to use jQuery to submit a form, have PHP process it, and give output/feedback to users while they wait (either in a div or an iframe...in the example below I use an iframe).
I have the backbone of the xhr version that I found online, but I was wondering if there is a better way (I am aware that there is jquery mixed into this:
function submitForm(){
$('#report_iframe').attr('src','/tests/stream_ajax/blank_iframe.php');
$("#report_modal").modal({backdrop: "static"});
count=1;
xhr = new XMLHttpRequest();
xhr.open("GET", "/folder/ajax_result.php", true);
xhr.onprogress = function(e) {
count = count +1;
$( "#report_iframe" ).contents().find( "#content_loader" ).text('this is jquery count' + count);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
//console.log("Complete = " + xhr.responseText);
// alert("complete");
document.getElementById("report_iframe").srcdoc=xhr.responseText;
}
}
xhr.send();
};
Any help appreciated. Thanks.
J Doyle
Anyway you are using JQuery. Why don't you use JQuery ajax ?
$.ajax({
cache: false,
async: true,
type: "GET",
url: '/folder/ajax_result.php',
beforeSend:function()
{
count = count +1;
},
success:function(response)
{
document.getElementById("report_iframe").srcdoc=response;
}
});
I agree with #Nandan, you should use JQuery Ajax, now for the part of the progress feedback you should add an EventListener for the xhr object and display it in your frame, it would be something like this:
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var count = evt.loaded / evt.total;
$("#content_loader").html('this is jquery count ' + count*100);
}
}, false);
return xhr;
},
type: 'GET',
url: "/folder/ajax_result.php",
data: {},
success: function(data){
//Do something
}
});
For a better explanation and more information:
Click here
Or here
UPDATE:
You could also try something like this, it works well for download progress
$.ajax({
type: 'GET',
url: "/folder/ajax_result.php",
data: {},
xhrFields: {
onprogress: function (e) {
if (e.lengthComputable) {
$("#content_loader").text("this is jquery count " + e.loaded / e.total * 100 + "%");
}
}
},
success: function(data){
//Do something
}
});
I have this ajax-loaded #container and I'm trying to get it to play nice with some of my plugins. So far I managed to get scrollTo and a lightbox working inside this "container of death" using jquery.live but no luck with my fancy "add to cart" buttons. I've been playing around with .delegate, the livequery plugin, etc., for a few days now but I'm really not advanced enough to figure out what goes where. (I have a pretty shallow understanding of what I'm doing.)
Here's my shopping cart plugin, it's fairly small and straightforward. Can you give suggestions on what (.live, .delegate, or .livequery, or perhaps something else entirely) should be inserted where?
(Note: shopme p = the add to cart buttons, which need to be inserted inside the ajax-loaded "container of death." The rest of the cart exists outside said container and works fine since it's not ajax'ed in.)
$(document).ready(function(){
$('.wooo').bloooming_shop();
$('body').append('<div id="panel"><div id="panelcontent"></div><div class="panelbutton" id="hidepanel" style="display: none;"><a><font class="cartfont2">hide cart</font></a></div></div><div id="showpanel" class="panelbutton" style="display: visible;"><a><font class="cartfont">shopping cart</font></a></div><div id="btntarget"></div>');
$('#panelcontent').hide();
$.ajax({
type: "GET",
url: "/wooo/cart.php",
async: false,
dataType: "html",
success: function(html){
$('#panelcontent').html(html);
}
});
$(".panelbutton").click(function(){
$("#panel").animate({
height: "200px"
}, "fast",function(){
$('#panelcontent').show();
});
$("#hidepanel").fadeIn();
$("#showpanel").fadeOut();
});
$("#hidepanel").click(function(){
$("#panel").animate({
height: "0px"
}, "fast", function(){
$("#showpanel").fadeIn();
$('#panelcontent').hide();
});
$("#hidepanel").fadeOut();
});
// START 'ADD TO CART' BUTTONS
$('.shopme p').click(function(){
var pid = $(this).attr('rel');
$('body').prepend('<div class="shadow" id="'+$(this).attr('rel')+'_shadow"></div>');
var shadow = $('#'+pid+'_shadow');
shadow.width($(this).parent().css('width')).height($(this).parent().css('height')).css('top', $(this).parent().offset().top).css('left', $(this).parent().offset().left).css('opacity', 0.5).show();
shadow.css('position', 'absolute');
shadow.animate( {
width: $('#btntarget').innerWidth(),
height: $('#btntarget').innerHeight(),
top: $('#btntarget').offset().top,
left: $('#btntarget').offset().left
}, {
duration: 2000
} )
.animate({
opacity: 0
},
{
duration: 700,
complete: function(){
shadow.remove();
}
});
var option = $('#'+pid+' .woooptions').val();
var formData = 'pid=' + pid + '&option=' + option;
$.ajax({
type : 'POST',
url : '/wooo/cart.php',
data : formData,
success : function (html) {
$('#panelcontent').html(html);
}
});
});
$('.removeitem').live('click', function() { // .LIVE is used here
rid = $(this).attr('id');
rop = $(this).attr('rel');
var remData = 'remove=' + rid + '&rop=' + rop;
$.ajax({
type : 'POST',
url : '/wooo/cart.php',
data : remData,
success : function (html) {
$('#panelcontent').html(html);
// alert('thx');
}
});
});
}); // document
function checkOut(){
jQuery.ajax({
url: "/wooo/cart.php",
type: "POST",
data : "destroysession=true",
success: function(data, textStatus, jqXHR){
if(data){
window.location.href=jQuery('a.checkout').attr("data-href");
}else{
console.log("There is no data!")
}
},
error: function(jqXHR, textStatus, errorThrown){
console.log("AJAX ERROR: "+errorThrown)
}
});
}
/** replace ******/
jQuery.fn.bloooming_shop = function(){
this.each(function(){
var elem = $(this);
var cl = 'bt1';
var id = $(this).html();
var opt = $(this).attr('options');
var text = $(this).attr('text');
var price = $(this).attr('price');
// alert(price);
if (text == undefined) {
text = 'add to cart';
}
if (opt == 'true' && price != 'true' ) {
cl = 'bt3';
}
if (price == 'true' && opt == 'true') {
cl = 'bt4';
}
if (price == 'true' && opt != 'true') {
cl = 'bt2';
}
elem.removeClass('wooo');
elem.addClass('shopme');
elem.addClass(cl);
elem.attr('id','pid'+id);
elem.html('<p rel="pid'+id+'" class="'+cl+'">'+ text +'</p>');
// get product data
if (price == 'true' || opt == 'true') {
$.ajax({
type : 'GET',
url : '/wooo/functions.php?mode=p_data&id='+id+'&opt='+opt+'&price='+price,
success : function (html) {
elem.append(html);
if (jQuery().sSelect) {
elem.children('.woooptions').sSelect();
}
// change price
$('.woooptions').change(function(){
var selid = $(this).attr('id');
var rel = $('#'+selid+' option:selected').attr('rel');
if (rel != undefined) {
$(this).parent().children('.woooprice').html(rel);
}
});
}
});
}
});
return false;
};
How do I keep this plugin alive, even within ajax'ed-in #container? I really just need the 'add to cart' buttons (shopme p) to be in said container div. Thank you.
.live("click", function(){
instead of just click.