PHP/JS Unlimited scroll loading all data from MySQL in one scroll - javascript

I was working on Unlimited scroll for my website using PHP and JavaScript. I almost made it but there was a problem In my code, after scrolling to the bottom of the page my script should load 15 articles every time I scroll to the bottom and after its done It stops loading more posts, but instead it loads all of the articles and then stops the script when all of the posts are loaded.
My JavaScript code:
<script>
// Unlimited Scroll
$(document).ready(function() {
$('.post-load').hide();
var load = 0;
var nbr = "<?php echo mysql_num_rows($sql); ?>";
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('.post-load').show();
load++;
if (load * 15 > nbr) {
$('.post-load').hide();
} else {
$.post("extensions/ajax.php", {
load: load
}, function(data) {
$('.lb').append(data);
$('.post-load').hide();
});
}
}
});
});
extensions/ajax.php File for loading the posts through PHP:
<?php
include 'connect.php';
$load = htmlentities(strip_tags($_POST['load'])) * 2;
$sql = mysql_query("SELECT * FROM articles ORDER BY postNum DESC");
$countBlop = mysql_num_rows($sql);
$queryL = mysql_query("SELECT * FROM articles ORDER BY postNum DESC LIMIT 15,".$countBlop."");
while ($posts = mysql_fetch_assoc($queryL)) {
?>
<div class="article">Echo the posts...</div>
<?php } ?>

Looks to me like your LIMIT syntax is backwards
LIMIT 15,".$countBlop.
should be
LIMIT ".$lastIndex.",15
As is now it would be starting at record 15 and then continuing to load until you reach the total count(as defined by $countBlop)
You will also need to have a way for jQuery to pass the last index to the ajax call.

Related

Scroll to bottom of item on Ajax load

I am creating a kind of messaging system with php and jQUERY, when you click on users profile and hit the messaging button it take us to the message page, it takes about 2sec to load previous message, so I added a code to scroll to bottom of the div class containing all message item once the ajax is loaded, to show latest messages , but the problem I am having is when I try to scroll up back I am having issues , the moment i try to scroll up due to the code i added it goes down on its own, any solution would be well appreciated.
Here is my JQ code - if there is anything else I can provide to help me solve this issue, I would do so quickly.
$(document).ready(function(){
/*post message via ajax*/
//get message
var c_id = $("#conversation_id").val();
//get new message every 2 second
setInterval(function(){
$(".display-message").load("get-message-ajax.php?c_id="+c_id , stateChange);
}, 2000);
});
function stateChange() {
var newstate = true;
if(newstate = true){
$(".conversation_history.clearfix").animate({
scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight
}, 1000)} else {
$(".conversation_history.clearfix").end();
var newstate = false;
}
}
Code from get_message-ajax.php
<?php
include 'db.php';
include 'function.php';
/*Get Message*/
if(isset($_GET['c_id'])){
$conversation_id = base64_decode($_GET['c_id']);
$querynew = "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'";
$mysqli_q_new = mysqli_query($connection, $querynew);
confirmQuery($mysqli_q_new);
if (mysqli_num_rows($mysqli_q_new) > 0 ){
while($user_real_info = mysqli_fetch_assoc($mysqli_q_new)){
$trap_user_from = $user_real_info['user_from'];
$trap_user_to = $user_real_info['user_to'];
$trap_user_message = $user_real_info['message'];
$querynew2 = "SELECT profile_image,firstname FROM `users` WHERE id='$trap_user_from'";
$mysqli_q_new2 = mysqli_query($connection, $querynew2);
confirmQuery($mysqli_q_new2);
$user_fetch = mysqli_fetch_assoc($mysqli_q_new2);
$user_form_username = $user_fetch['firstname'];
$user_form_img = $user_fetch['profile_image'];
?>
<div class='conversation_history_inner clearfix'>
<span><?php echo $user_form_username; ?> </span>
<div class='converstion_history_image img-is-responsive pull-left'>
<?php echo getUserImage($user_form_img) ?>
</div>
<div class='converstion_history_chat'>
<p><?php echo $trap_user_message; ?></p>
</div>
</div>
<?php
}
}
} else {
echo 'nth found';
}
?>
I'm assuming you only want to scroll down when it gets the first message. If so, I would suggest changing the stateChange function into this:
var scrolled = false;
function stateChange() {
if(!scrolled){
$(".conversation_history.clearfix").animate({scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight}, 1000);
scrolled = true;
}
}
This will make it only scroll down the first time it gets a new message instead of every time like it currently does.
The content is scrolling to bottom automatically because you have used setInterval function which will trigger at a constant interval of time. Use setTimeOut instead it will call only once after the specified time. Look here for more details

ajax request makes page lag

I have this ajax request code
function hehe2(){
var a = $(".film2numb").val();
return $.ajax({
type : "GET",
url : "php/controller1.php?page=semuafilm",
data : "data="+a,
cache: false,
success: function(data){
$('.semuafilm').load('php/film.php');
},
});
}
and it requests this php code, basically it prints out HTML data from SQL
<?php
$indicator = $_SESSION['p'];
if ($indicator == 'filmbaru') {
# code...
$batas = $_SESSION['a'];
if (!$batas) {
$batas = 1;
}
if ($batas>1) {
$batas = $batas * 8;
}
include('connect.php');
$queryfilm = "select * from tb_film order by film_year desc, film_id desc limit $batas ,8";
$exec = $conn->query($queryfilm);
while ( $f = $exec->fetch_assoc()) {
$tn = str_replace(" ","-",$f['film_name']) ;
?>
<div class='col l3 m3 s6 itemovie'><div><img src="images/dum.jpg" class="lazy" data-original='http://www.bolehnonton.com/images/logo/<?php echo $f["film_logo"]; ?>' width="214" height="317"><div><div><div><p><b><?php echo $f['film_name']; ?></b></p><p>IMDB Rating</p><p><?php echo $f['film_genre']; ?></p><p class='center-align linkmov'><a class='dpinblock browntex' href='?page=movie&filmname=<?php echo $tn; ?>'>PLAY MOVIE</a></p><p class='center-align linkmov'><a class='dpinblock' href=''>SEE TRAILER</a></p></div></div></div></div></div>
<?php
}
?>
and here is the controller
<?php
session_start();
$a = $_GET['data'];
$p = $_GET['page'];
$g = $_GET['genre'];
$_SESSION['a'] = $a;
$_SESSION['p'] = $p;
$_SESSION['g'] = $g;
?>
My question is why every time I click button that binded to the hehe2() function (4-5 times, which requested a lot of images) the page get heavier as I click incrementally(laggy, slow to scroll), is there a way to make it lighter, or is there a way to not store image cache on page or clear every time I click the button that binded to hehe2() function?
I am not sure that my advice will be helpful, I will just share my experience.
First of all you should check your binding. Do you bind click trigger only once?
Sometimes function binds multiple times and it can slow down the page.
You can put code below inside function and check the console
console.log("Function called");
If everything is fine from that point and function fires only once - I would recommend you to change flow a little bit. Is it possible to avoid many clicks in a row? If it is not big deal - you can disable button on click, show loader and enable button when AJAX request is completed. This approach will prevent from making multiple requests at once at page will be faster.

Scroll Load More SQL Limit

So I have this website laid out and made but now I need to load more results on scroll. This has been asked on here a million times but I was wondering if there was a simple way to fit into my build. Ideally I'd like to do something with the limit but everything I've seen has been about having an entirely seperate page.
Page example-
$sql = "SELECT * FROM `Products` ORDER BY id LIMIT 0,4 ";
echo "<div class=\"full_container\">";
echo "<div class=\"full\">";
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class=\"item_frame\">";
echo "<div class=\"item\">";
echo "<h5>".$row["Name"]."</h5>";
echo "</div>"; #Item End#
echo "</div>"; #Item_Frame End#
JS example-
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
///Where I would have the limit fix
}
});
Would this be able to easily be switched to be able to load more on scroll or do I have to go with the second php page to go with ajax?
To get more information you would probably have to do a call via ajax and then render the new images with the javascript once the data is returned. You could treat this in the same way you would for regular pagination, just remember how many results you've got and enter that into your limit so something like
(function () {
var page = 2,
uri = 'moreImages.php';
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
$.get (uri, {page: page}, function (data) {
page ++;
$('#container').append (data);
});
}
});
}) ();
Then in your PHP page you just need to work out the offset based on your pagination rules
$page = (int) #$_GET['page'] ?: 1;
$numItems = 4;
$start = ($page - 1) * $numItems;
$sql = "SELECT * FROM `Products` ORDER BY id LIMIT {$start}, {$numItems}";
Almost forgot:
It might also be worth sending the request a bit before they get to the bottom of the page to speed things up. Make sure to set a flag in your code to mark that you're waiting for the information and only request more when it's clear or you'll constantly be sending requests while scrolling about.

cannot impliment infinite scroll with my code

I've read multiple examples on infinite scrolling, but I find it hard to implement it to my code. Here's the code, where data get shown from MySQL database :
<div class="container" align="center" style="margin-top:100px;margin-bottom:100px"><div class="row">
<?php
$result = mysql_query("SELECT * FROM batai WHERE svarbumas=1 ORDER BY id DESC");
while ($row = mysql_fetch_array($result))
{
extract($row);
$link=$row["linkas"];
echo "<div class='col-md-4'>";
$sites_html = file_get_contents($link);
$html = new DOMDocument();
#$html->loadHTML($sites_html);
$meta_og_img = null;
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
//If the property attribute of the meta tag is og:image
if($meta->getAttribute('property')=='og:image'){
//Assign the value from content attribute to $meta_og_img
$meta_og_img = $meta->getAttribute('content');
}
}
list($width, $height) = getimagesize($meta_og_img);
$skaicius = abs($width - $height);
if($width > $height) {
echo "<img src=\"$meta_og_img\" style='height:234px;margin-left:-33%' onclick='window.open(\"$link\", \"_blank\");'>";
}
else if($width < $height) {
if($skaicius < 100){
echo "<img src=\"$meta_og_img\" style='width:234px'
onclick='window.open(\"$link\", \"_blank\");'>";
}
else {
echo "<img src=\"$meta_og_img\" style='width:234px;margin-top:-33%'
onclick='window.open(\"$link\", \"_blank\");'>";
}
}
echo "</div>";
}
?>
Stored in the database is a link to, for example, a internet shop page. What the code does is it takes a image for facebook preview from the link stored in the db, which is tagged og:image and then positions it to center. The problem is that page tries to load every image and that takes a ton of time to load the page, thats why I want to somehow make it into a load on scroll page. Btw, Im using Bootstrap's grid system here. I hope you can help me. P.S. If you don't get what I mean because of my bad english, ask me and I'll try to answer it more clearly

Refreshing php page without reloading content?

I've searched everywhere for a method where a page can reload automatically for every x seconds without actually reloading the page's contents, I have php code(includes some html) which updates my database table whenever a new user joins the page. However this only works once.
PHP CODE
<?php
$userOn5 = "SELECT * FROM `usersOn` WHERE name = '$username'";
$query4 = mysql_query($userOn5) or die (mysql_error());
while ($row = mysql_fetch_array($query4)) {
// Gather all $row values into local variables for easier usage in output
$timenow = $row["time"];
}
$user = "SELECT * FROM `user`";
$query3 = mysql_query($user) or die (mysql_error());
while ($row = mysql_fetch_array($query3)) {
$usernow = $row["name"];
}
$secs = time() - $timenow;
mysql_query("UPDATE user SET name = '$user'");
if ($username == $usernow) {
?>
<div id="container" style="display:none;">
I've attempted using meta tag but that reloads the entire content, I've attempted moving the entire php code to a separate php file and tried loading it inside a div called 'show' in the page:
var auto_refresh = setInterval(
function ()
{
$('#show').load('registeruser.php').fadeIn("slow");
}, 10000); // autorefresh the content of the div after
//every 10000 milliseconds(10sec)
Basically what I'm trying to do is rerun the php code every 10 seconds. Help?
Quite likely your issue is due to browser cache. You can use the following workaround -- that's actually what ajax does when you use cache: false:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t);
$('#container').fadeIn("slow");
}, 10000);
});
UPDATE
Alternatively, you can use the following:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t).find('> div').fadeIn("slow");
}, 10000);
});

Categories

Resources