PHP Infinite scroll pulling random results? - php

I have a page that returns 16 records from my table.
As the user scrolls to the bottom, I then pull another 12 records from my table and append them to my previous results, my problem is that my results are being duplicated, and not in the correct order.
JS
// Ajax Getentries.php
var url = location.pathname;
if(url.indexOf('missing-people.php') > -1) {
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if(didScroll) {
didScroll = false;
if(($(document).height() - $(window).height()) - $(window).scrollTop() < 100) {
var number = $(".directory").children().length;
$.ajax({
type: "POST",
url: "getentries.php",
data: "count=" + number,
success: function (results) {
$('.directory').append(results).fadein();
}
});
}
}
}, 250);
}
PHP
$result = mysql_query("SELECT * FROM directory LIMIT {$_POST['count']},12");
$c = 1;
while($row = mysql_fetch_array($result))
{
echo '<div class="entry';
if (($c % 4) == 1) echo ' alpha ';
echo ' span3"><span class="name">' . $row['First_Name'] . ' ' . $row['Surname'] . "</span>";
echo '<img src="/access/upload/' . $row["picture_1"] . '" alt="' . $row['First_Name'] . ' ' . $row['Surname'] . ', missing since ' . $row['Date_Last_Seen'] . ' " />';
echo '<span class="missing-from">Last seen in ' . ucwords($row["Location_County_Last_Seen"]) . '</span>View Profile</div>';
$c++;
}
mysql_close($con);

it seems like it's a race condition. Indeed, if you quickly scroll the page this is what happens:
the setInterval gets triggered
there are already 12 images in the dom, hence var number = $(".directory").children().length is 12.
now new data is fetched from the server with ajax.
Now, if I'm still at the bottom of the page and the ajax calls hasn't completed yet, the setInterval is going to be triggered again, number still resolve to 12 and I'm going to do the same ajax request. Hence duplication.
Solving the issue could be as simple as setting number at the beginning of the script and incrementing it every time you make an ajax call.
// Ajax Getentries.php
var url = location.pathname;
var number = $(".directory").children().length;
if(url.indexOf('missing-people.php') > -1) {
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if(didScroll) {
didScroll = false;
if(($(document).height() - $(window).height()) - $(window).scrollTop() < 100) {
number += 12;
$.ajax({
type: "POST",
url: "getentries.php",
data: "count=" + number,
success: function (results) {
$('.directory').append(results).fadein();
}
});
}
}
}, 250);
}

Related

Load multiple data from database with ajax and slickAdd them to existing Slick on success, but only once

so I'm using Slick Carousel and I'm showing in it a list of products from my database limited to 24 for performance reasons. But I need to show all of them, so I made a function that ajax loads another 24 products everytime the user is 2 slides before the end and add them with slickAdd function to the existing Slick. Everything is working great but it takes a few seconds till it gets added because the slickAdd function runs for each new product. So I wanted to ask if there is a way to select all the 24 new products, and add them only once with the slickAdd function.
This is my current code
$('.demo').on('beforeChange', function(event, slick, currentSlide, nextSlide){
var komponent = $(".komponent-container.active").attr("id");
var slideCount = slick.slideCount-6;
console.log(slick.slideCount);
if(nextSlide == slideCount){
console.log("loadmore");
$.ajax({
type: "POST",
url: "/project/public/konfigurator",
data: {id: komponent, from_column: slick.slideCount, requestid: "load_more"},
dataType: "json",
success: function (data) {
var data_parser = JSON.parse(data)[0];
if (data_parser.length > 0) {
for (i = 0; i < data_parser.length; i++) {
var produkt_nazov = 0;
if (data_parser[i].produkt.length > 45) {
produkt_nazov = data_parser[i].produkt.substring(0, 45) + "...";
} else {
produkt_nazov = data_parser[i].produkt;
}
$('.demo').slick('slickAdd', '<div><div><div class="item-container"><div class="container-wrapper"><div class="produkt-container"><div class="item-left"><div class="item-image-wrapper"><img draggable="false" id="produkt-img" src="img/konfigurator/'+komponent+'/' + data_parser[i].produkt + '/1.jpg" alt="" /></div><div class="cena">' + data_parser[i].cena + ' €</div></div><div class="item-right"><div class="item-info"><span class="item-title">' + produkt_nazov + '</span><span class="item-description"><span>Výrobca čipu - ' + data_parser[i].vyrobca_cipu + '</span><span>Veľkosť pamäte - ' + data_parser[i].vram_size + '</span><span>Typ pamäte - ' + data_parser[i].vram_type + '</span><span>Frekvencia jadra - ' + data_parser[i].gpu_memory_clockrate + '</span></span></div><div class="spodna-cast"><div class="action-buttons"><a class="detail-button">Detail</a><a class="add-button">Vybrať</a></div></div></div></div></div></div></div></div>');
console.log("add");
}
}
},
error: function (result) {
alert('error');
}
});
}
});
And sorry if there is any gramatical mistakes, english is not my first language.
I tried to move the SlickAdd function outside the for(), but it added only 1 product to the Slick.
I figured it out, leaving it here for others.
var html = '';
for (i = 0; i < data_parser.length; i++) {
var produkt_nazov = 0;
if (data_parser[i].produkt.length > 45) {
produkt_nazov = data_parser[i].produkt.substring(0, 45) + "...";
} else {
produkt_nazov = data_parser[i].produkt;
}
html += '<div><div><div class="item-container"><div class="container-wrapper"><div class="produkt-container"><div class="item-left"><div class="item-image-wrapper"><img draggable="false" id="produkt-img" src="img/konfigurator/' + komponent + '/' + data_parser[i].produkt + '/1.jpg" alt="" /></div><div class="cena">' + data_parser[i].cena + ' €</div></div><div class="item-right"><div class="item-info"><span class="item-title">' + produkt_nazov + '</span><span class="item-description"><span>Výrobca čipu - ' + data_parser[i].vyrobca_cipu + '</span><span>Veľkosť pamäte - ' + data_parser[i].vram_size + '</span><span>Typ pamäte - ' + data_parser[i].vram_type + '</span><span>Frekvencia jadra - ' + data_parser[i].gpu_memory_clockrate + '</span></span></div><div class="spodna-cast"><div class="action-buttons"><a class="detail-button">Detail</a><a class="add-button">Vybrať</a></div></div></div></div></div></div></div></div>';
}
$(".demo").slick('slickAdd', html);
console.log("add");

Jquery Scroll Loading All The Rows At Once And Should Only Load 5 At A Time

I am using the following script to load more, 5 rows at a time from the database, on scroll. All the rows are loading at once on scroll after the initial loads correctly. In realtime, the first 5 load. Then on scroll the last 14 load at once. Like it rushes to the end instead of incrementally loading 5 at a time. I use the same code for a load more button and it works fine. Same PHP file for both. No issue with that. Can anyone see why all the rows are being loaded on scroll instead of 5 at a time.
<script>
//SET NUMBER OF ROWS TO DISPLAY AT A TIME
rowsPerPage = 5;
$(document).ready(function() {
// GETTING DATA FROM FUNCTION BELOW
getData();
window.onscroll = function() {
if ($(window).scrollTop() >= $('#load-container').offset().top + $('#load-container').outerHeight() - window.innerHeight) {
$('#load-more').html('Loading...');
var rowID = Number($("#row-id").val());
var allCount = Number($("#count").val());
rowID += rowsPerPage;
if (rowID <= allCount) {
$("#row-id").val(rowID);
getData();
} else {
$('#load-more').html('End Of Data');
//$('#load-more').html('');
}
}
}
/* REQUEST DATA */
function getData() {
var rowID = $("#row-id").val();
var allCount = $("#count").val();
$('#load-more').html('Loading...');
$.ajax({
url: 'promotions/newest-load-scroll-data-invalid.php',
type: 'post',
data: {
rowID: rowID,
rowsPerPage: rowsPerPage
},
dataType: 'json',
success: function(response) {
setTimeout(function() {
loadData(response)
}, 1000);
},
});
}
/* LOAD DATA TO PAGE */
function loadData(data) {
var dataCount = data.length;
for (var i = 0; i < dataCount; i++) {
if (i == 0) {
var allCount = data[i]['allcount'];
$("#count").val(allCount);
} else {
var promoID = data[i]['promoid'];
var promoNameNewest = data[i]['promoname'];
var promoNameNewestVideo = data[i]['promoname'];
var promoRefNum = data[i]['promorefnum'];
var promoType = data[i]['promotype'];
var theBanner = data[i]['thebanner'];
var email = data[i]['email'];
var customerType = data[i]['customerType'];
if (email == "") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="visitor-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="visitor-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
if (customerType == "p") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="advertiser-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="advertiser-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
}
$('#load-more').html('Loading...');
}
}
});
</script>
I was able to utilize flags to make it work right with a couple other small changes. Appreciate the input, Taplar.

Handling Infinite Scroll Effect Jquery and PHP

Why is the url I created getting 404 instead of loading the page data set to each group I want to show on scroll?
I implemented a infinite scroll effect to paginate my data from a table in my mysql database. Now that I am trying to load the page I am getting a 404 error for the url my query is creating.
example.com/inventory-search.php?limit=15&offset=0&_=1455489762864 404 (Not Found)
I am operating under the impression that the url being formed was specifying the amount of pages and my logic should be keeping track on which page set to be shown. Loading more on scroll.
I did use a tutorial online to get this part of the logic done so I am wondering if I am assuming something that is wrong.
My code looks like this,
DB Config
$db_host = "localhost";
$db_user = "username";
$db_pass = "password";
$db_name = "dbName";
try
{
$DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
?>
Inventory search script,
<?php
require_once get_stylesheet_directory() . '/wuno-search/Dbconfig.php';
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 15;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
?>
My Jquery
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = false;
var limit = 15;
var offset = 0;
var assetPath = "<?php echo $assetPath; ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
busy = true;
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
define $assetPath
$assetPath = get_stylesheet_directory() . '/wuno-search/inventory-search.php';
?>
There are a number of things that could be factors, but what may be the biggest issue is that you are trying to access result properties that you have not SELECTed. For example, you are trying to get $res['wuno_product'] when you have only selected id in your query. You can always do a print_r($results) or var_dump($results), etc. to see what the query is returning.

Ajax request returns nothing. why?

Below is the ajax request.
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(deleted, undeleted){
if(undeleted == 0) {
alert('All ' + deleted + ' files delted from the server');
} else {
alert(deleted + ' files deleted and ' + undeleted + ' files could not be deleted');
}
}, 'json');
and here goes the delete.php
<?php
if(isset($_POST['deletearray'])) {
$files = $_POST['deletearray'];
$dir = $_POST['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
echo json_encode($deleted, $undeleted);
}
return;
?>
Up on running the code it deletes the files successfully but no message displays.
I also tried changing the ajax request as:
$.post('delete.php', {deletearray:deletearray, dir:dir}, function(deleted, undeleted){
alert("php finished");
}, 'json');
still it does not display the message. So i guess something is wrong in the delete.php file. Please help.
First thing-
Use $_POST['deletearray'] instead of $_POST[deletearray]
Second thing-
You cannot return different variables from the PHP scrtipt, every thing you print there is returned in the ajax callback, so just write this-
PHP
json_encode(array('totalDeleted' => $deleted, 'totalUndeleted' => $undeleted));
AJAX
...
function(response){
response=JSON.parse(response);
console.log(response);
}
The best way to do jquery + ajax + php is as next:
jquery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function do_ajax() {
//set data
var myData = new Array();
myData.push({name:'deletearray',value:'deletearray'});
myData.push({name:'dir',value:'dir'});
//ajax post
$.ajax({
dataType: 'json',
url: 'delete.php',
type: 'post',
data: myData,
success: function(returnData) {
if(returnData.undeleted == 0) {
alert('All ' + returnData.deleted + ' files delted from the server');
} else {
alert(returnData.deleted + ' files deleted and ' + returnData.undeleted + ' files could not be deleted');
}
}
});
}
</script>
PHP:
<?php
$myData = $_POST;
if(isset($myData['deletearray']) AND isset($myData['dir'])) {
$files = $myData['deletearray'];
$dir = $myData['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
print(json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted)));
exit();
}
?>
You should use json_encode like following:
json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted));
And you have to get vars with data.undeleted and data.deleted
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(data) {
if(data.undeleted == 0) {
alert('All ' + data.deleted + ' files delted from the server');
} else {
alert(data.deleted + ' files deleted and ' + data.undeleted + ' files could not be deleted');
}
}, 'json');

How can I create a dynamic tag with ajax call?

I want to create icons according to the number of passengers and I want to give each icon an id.The passenger ids is in php code.How can I give the id of the passenger to the icon id.When par_key is id, par_value should be id of that passenger.
function sta_callStation() {
var distName;
var count = 0;
$('#noOfPassengers, #infoOfPassengers, #distType,#distParams').empty();
$('#sta_numberOfIcons').empty();
$.getJSON('StationInfoGenerator.php', function (station) {
$.each(station, function (sta_key, sta_value) {
if (sta_key == "numberOfPassengers") {
$('#noOfPassengers').append("<strong>İstasyondaki Yolcu Sayısı: </strong>" + sta_value);
}
if (sta_key == "passengers") {
$('#infoOfPassengers').append("<strong>Passengers Information:</strong>" + '<br/>');
$.each(station.passengers, function (i, passenger) {
// $('#sta_numberOfIcons').append('<i class="icon-user"
id = "sta_numberOfIcons" > < /i>');
$.each(passenger, function(par_key, par_value)
{
if(par_key=="pas_id")
{
var icon = document.createElement("i");
// icon.id = par_value;
input.setAttribute("id", par_value);
icon.setAttribute("class", "icon-user");
document.getElementById("sta_numberOfIcons").appendChild(icon);
}
$(function () {
$("#sta_numberOfIcons").popover({
title: 'Passenger Information',
content: (par_key + ': ' + par_value + ' ' + '<br/>')
});
$('#infoOfPassengers').append(par_key + ': ' + par_value + ' ' + '<br/>');
});
});
$('#infoOfPassengers').append('<hr />');
count++;
});
}

Categories