How to load values to page while scrolling the page - php

I have a table named "User" with more than 3k rows in MySql database.I want to fetch the database while scrolling the page(As like Facebook news feeds). I surfed for a long time but I can't get it. hoping positive response as soon as possible.
thank you!

If I understood what did you mean:
Database Table
CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT);
load_data.php
When we are scrolling down a webpage, the script($(window).scroll) finds that you are at the bottom and calls the last_msg_funtion(). Take a look at $.post("") eg: $.post("load_data.php?action=get&last_msg_id=35")
<?php
include('config.php');
$last_msg_id=$_GET['last_msg_id'];
$action=$_GET['action'];
if($action <> "get")
{
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function last_msg_funtion()
{
var ID=$(".message_box:last").attr("id");
$('div#last_msg_loader').html('<img src="bigLoader.gif">');
$.post("load_data.php?action=get&last_msg_id="+ID,
function(data){
if (data != "") {
$(".message_box:last").after(data);
}
$('div#last_msg_loader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_msg_funtion();
}
});
});
</script>
</head>
<body>
<?php
include('load_first.php'); //Include load_first.php
?>
<div id="last_msg_loader"></div>
</body>
</html>
<?php
}
else
{
include('load_second.php'); //include load_second.php
}
?>
load_first.php
Contains PHP code to load 20 rows form the message table.
<?php
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" >
<?php echo $msg; ?>
</div>
<?php
}
?>
load_second.php
Contains PHP code to load 5 rows less than last_msg_id form the message table.
<?php
$last_msg_id=$_GET['last_msg_id'];
$sql=mysql_query("SELECT * FROM messages WHERE mes_id < '$last_msg_id' ORDER BY mes_id DESC LIMIT 5");
$last_msg_id="";
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" >
<?php echo $msg;
?>
</div>
<?php
}
?>
CSS
body
{
font-family:'Georgia',Times New Roman, Times, serif;
font-size:18px;
}
.message_box
{
height:60px;
width:600px;
border:dashed 1px #48B1D9;
padding:5px ;
}
#last_msg_loader
{
text-align: right;
width: 920px;
margin: -125px auto 0 auto;
}
.number
{
float:right;
background-color:#48B1D9;
color:#000;
font-weight:bold;
}
Take a look at live demo and scroll down.
Regards,
Ivan

Check out http://jscroll.com/ or just google for "jQuery load content while scrolling" or "jQuery infinite scroll" for other alternatives.

Related

Infinite Scroll Pagination using PHP and jQuery returns only few posts and halts with a loader gif

I m trying to replicate code found online for Infinite scroll using PHP and JQuery.
But unfortunately, there is a flaw in the code which makes it only to return 7 posts only and stops fetching other posts upon scrolling down leaving a loader gif at the bottom.
Generally, I wouldn't have asked this question, but the code seems
pretty nice (in laymans terms) which I presume will be very helpful
for rookies like me in the community.
Meanwhile will search other resources and try to answer it by myself.
My code Goes as :
Index.php
<div class="post-wall">
<div id="post-list">
<?php
require_once ('db.php');
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
$sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT 7";
$result = mysqli_query($conn, $sqlQuery);
?>
<input type="hidden" name="total_count" id="total_count"
value="<?php echo $total_count; ?>" />
<?php
while ($row = mysqli_fetch_assoc($result)) {
$content = substr($row['content'], 0, 100);
?>
<div class="post-item" id="<?php echo $row['id']; ?>">
<p class="post-title"><?php echo $row['title']; ?></p>
<p><?php echo $content; ?></p>
</div>
<?php
}
?>
</div>
<div class="ajax-loader text-center">
<img src="LoaderIcon.gif"> Loading more posts...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
windowOnScroll();
});
function windowOnScroll() {
$(window).on("scroll", function(e){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
if($(".post-item").length < $("#total_count").val()) {
var lastId = $(".post-item:last").attr("id");
getMoreData(lastId);
}
}
});
}
function getMoreData(lastId) {
$(window).off("scroll");
$.ajax({
url: 'getMoreData.php?lastId=' + lastId,
type: "get",
beforeSend: function ()
{
$('.ajax-loader').show();
},
success: function (data) {
setTimeout(function() {
$('.ajax-loader').hide();
$("#post-list").append(data);
windowOnScroll();
}, 1000);
}
});
}
</script>
getMoreData.php
<?php
require_once('db.php');
$lastId = $_GET['lastId'];
$sqlQuery = "SELECT * FROM tbl_posts WHERE id < '" .$lastId . "' ORDER BY id DESC LIMIT 7";
$result = mysqli_query($conn, $sqlQuery);
while ($row = mysqli_fetch_assoc($result))
{
$content = substr($row['content'],0,100);
?>
<div class="post-item" id="<?php echo $row['id']; ?>">
<p class="post-title"> <?php echo $row['title']; ?></p>
<p><?php echo $content; ?></p>
</div>
<?php
}
?>
Any help is greatly appreciated.
I would set this up differently using classes and controllers etc, but as simple scripts, I might set it up something like:
Create a file called getData.php with this content:
<?php
require_once('db.php');
if (! function_exists('getData')) {
/**
* #param int $offset
* #param int $limit
* #return array|null
*/
function getData($offset, $limit, $conn) {
$offset = (int)$offset;
$limit = (int)$limit;
$sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $sqlQuery);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$rows[]= $row;
}
return $rows;
}
}
Create another file called index.php with this content:
<?php
require_once ('getData.php');
$offset = (int)($_GET['offset'] ?? 0);
$dataOnly = (int)($_GET['dataOnly'] ?? 0);
$limit = 7;
$rows = getData($offset, $limit, $conn);
$offset+= $limit;
$data = [
'rows' => $rows,
'offset' => $offset,
];
$data = json_encode($data);
// if this is an ajax call, stop here and just spit out our json
if ($dataOnly) {
echo $data;
exit;
}
// otherwise, render the page
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style type="text/css">
body {
font-family: Arial;
background: #e9ebee;
font-size: 0.9em;
}
.post-wall {
background: #FFF;
border: #e0dfdf 1px solid;
padding: 20px;
border-radius: 5px;
margin: 0 auto;
width: 500px;
}
.post-item {
padding: 10px;
border: #f3f3f3 1px solid;
border-radius: 5px;
margin-bottom: 30px;
}
.post-title {
color: #4faae6;
}
.ajax-loader {
display: block;
text-align: center;
}
.ajax-loader img {
width: 50px;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="post-wall">
<div id="post-list">
<input type="hidden" name="total_count" id="total_count" value="<?= $total_count ?>" />
<input type="hidden" name="offset" id="offset" value="<?= $offset ?>" />
</div>
<div class="ajax-loader text-center">
<img src="LoaderIcon.gif"> Loading more posts...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// load the initial rows on page load
let initialData = <?= $data ?? '' ?>;
if (initialData) {
if (initialData.rows) {
addrows(initialData.rows);
$('.ajax-loader').hide();
}
}
windowOnScroll();
});
function windowOnScroll() {
$(window).on("scroll", function(e){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
console.log('test');
if($(".post-item").length < $("#total_count").val()) {
let offset = $('#offset').val();
getMoreData(offset)
}
}
});
}
function getMoreData(offset) {
$('.ajax-loader').show();
$(window).off("scroll");
let pageUrl = window.location.href.split('?')[0];
$.ajax({
url: pageUrl + '?dataOnly=1&offset=' + offset,
type: "get",
success: function (response) {
response = JSON.parse(response);
if (response.rows) {
addrows(response.rows);
if (response.offset) {
$('#offset').val(response.offset);
}
$('.ajax-loader').hide();
}
windowOnScroll();
}
});
}
function addrows(rows) {
let postList = $("#post-list");
$.each(rows, function (i, row) {
let rowHtml = '<div class="post-item" id="'+row.id+'"><p class="post-title">'+row.title+'</p><p>'+row.content+'</p></div>';
postList.append(rowHtml);
});
}
</script>
</body>
</html>
Now, I cant test this locally so there might be an error or two in there, but that should give you the general idea.
One thing im not 100% sure of is that if ($(window).scrollTop() == $(document).height() - $(window).height()){ condition.
XSS warning
You dont show how these "posts" get added to the database, presumably they come from user submissions on some other form. If that is the case, make sure that you understand what XSS vulnerabilities are and how to prevent them

php pick data from web and show it in div

i have a div and also on same page i have some data which is show on web page i just want data show on div how can i do this? i am very very new in php .thanks here is the php file.
<?php
define('HOST','xxxxxxxxxxx');
define('USER','xxxxxxxxxxxxx');
define('PASS','xxxxxxxx');
define('DB','androidapi2');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from users WHERE status = 1";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
// 'id'=>$row[0],
'email'=>$row[3],
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
<html>
<head>
<title>DIC ChatBox Beta 1</title>
<style>
#usersOnLine {
font-family:tahoma;
font-size:12px;
color:black;
border: 3px teal solid;
height: 525px;
width: 250px;
float: right;
overflow-y:scroll;
}
.container{
width:970px;
height:auto;
margin:0 auto;
}
</style>
</head>
<body>
<div class="container">
</div>
<h2> all contacts</h2>
<div id="usersOnLine">
</div>
</div>
</body>
</html>
here is the div id usersonline where i want all data show . how to made it.
There is no need to use json_encode(array("result"=>$result));, directly use $result
<div id="usersOnLine">
<?php
foreach($result as $key => $val)
{
echo $val['email'];
echo "<br>";
}
?>
</div>
If you want to use it on another page
Creating New Session In php file
<?php
session_start(); ///at the top of this file
///after your query and creating array
$_SESSION["result"]= $result;////set $result in session
?>
Getting Session on another page
<?php
session_start();
if(isset($_SESSION["result"]))
{
$result = $_SESSION["result"];
///your foreach loop to print data
}
?>
READ SESSION DOCUMENTAION

Creating 5 Star Rating System With PHP , MySQL ,Jquery And Ajax

I've downloaded this tutorial http://megarush.net/5-star-rating-system-with-php-mysql-jquery-and-ajax/ but I'm getting these errors:
Notice: Undefined variable: rat in C:\xampp\htdocs\rating\rating.php on line 37
Notice: Undefined variable: v in C:\xampp\htdocs\rating\rating.php on line 41
<?php
include("settings.php");
connect();
$ids=array(1,2,3);
?>
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<link rel="stylesheet" href="rating.css" />
<script type="text/javascript" src="rating.js"></script>
</head>
<body>
<?php
for($i=0;$i<count($ids);$i++)
{
$rating_tableName = 'ratings';
$id=$ids[$i];
$q="SELECT total_votes, total_value FROM $rating_tableName WHERE id=$id";
$r=mysql_query($q);
if(!$r) echo mysql_error();
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
$j=$i+1;
$id=$ids[$i];
echo'<div class="product">
Rate Item '.$j.'
<div id="rating_'.$id.'" class="ratings">';
for($k=1;$k<6;$k++){
if($rat+0.5>$k)$class="star_".$k." ratings_stars ratings_vote";
else $class="star_".$k." ratings_stars ratings_blank";
echo '<div class="'.$class.'"></div>';
}
echo' <div class="total_votes"><p class="voted"> Rating: <strong>'.#number_format($rat).'</strong>/5 ('.$v. ' vote(s) cast)
</div>
</div></div>';}
?>
</body></html>
$rat and $v are being defined within the scope of your while loop.
If you declare them globally (outside the loop), the rest of your code will recognize them.
$rat = 0;
$v = 1;
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
See here:
http://bgallz.org/988/javascript-php-star-rating-script/
This combines a Javascript code that generated the URL for the different ratings given as well as the change in display for the stars before and after a rating is given.
An overlay DIV is displayed after the rating is given so that no immediate ratings can be given by the same. It also stores the user's IP address with the rating submission to prevent multiple ratings from one user.
This is a simple and easy to use script with just Javascript and PHP for star rating.
The problem is because of scoping of those variables. When you are trying to echo those variables outside the while loop; PHP can not find the varables as they were created (and assigned) inside the loop. To solve this, just assign a blank value to both variables outside too:
if(!$r) echo mysql_error();
$rat = 0;
$v = 1; // In case there are no records.
while($row=mysql_fetch_array($r))
{
$v = $row['total_votes'];
$tv = $row['total_value'];
$rat = $tv/$v;
}
Add this at line at beginning to nide notice error in your code .
error_reporting(E_ALL ^ E_NOTICE);
Most of time notice error do not affect the program.
In case if your votes are not recording then delete your cookies and try to vote from different IP address .This script has a feature to not accept votes from same ip or vistitor to avoid multiple votes by same users on same product.
var cname=document.getElementById(id).className;
var ab=document.getElementById(id+"_hidden").value;
document.getElementById(cname+"rating").innerHTML=ab;
for(var i=ab;i>=1;i--)
{
document.getElementById(cname+i).src="star2.png";
}
var id=parseInt(ab)+1;
for(var j=id;j<=5;j++)
{
document.getElementById(cname+j).src="star1.png";
}
Code from http://talkerscode.com/webtricks/star-rating-system-using-php-and-javascript.php
<style>
.star {
font-size: x-large;
width: 50px;
display: inline-block;
color: gray;
}
.star:last-child {
margin-right: 0;
}
.star:before {
content:'\2605';
}
.star.on {
color: red;
}
.star.half:after {
content:'\2605';
color: red;
position: absolute;
margin-left: -20px;
width: 10px;
overflow: hidden;
}
</style>
<div class="stars">
<?php
$enable = 5.5; //enter how many stars to enable
$max_stars = 6; //enter maximum no.of stars
$star_rate = is_int($enable) ? 1 : 0;
for ($i = 1; $i <= $max_stars; $i++){ ?>
<?php if(round($enable) == $i && !$star_rate) { ?>
<span class="<?php echo 'star half'; ?>"></span>
<?php } elseif(round($enable) >= $i) { ?>
<span class="<?php echo 'star on'; ?>"></span>
<?php } else { ?>
<span class="<?php echo 'star'; ?>"></span>
<?php }
}?>
</div>

Assign unique ID to div as created and then reference with jquery

I am brand new to php and a beginner with jQuery. I have a php page that is populated with data from a mySQL table. What I am trying to achieve is for the h3 that contains "View Job" to have a unique id assigned to it, as well as the div that prints out the job description. Then, I would like to reference these with jQuery so that if someone clicks View Job, only the description for that job will show. I hope this makes sense.
I tried this with classes and of course all the job descriptions revealed themselves when any View Job was clicked.
I tried the solution here, but this ended up with 36 "View Job" links on my page, and I need to assign the unique ID to the h3 and div as they are created.
I am open to suggestions for another way to achieve what I'm looking for - basically to hide/collapse each description as the user clicks on View Job for each job.
here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div#job-details").css("display" , "none");
$("h3#view-job").click(function() {
$("div#job-details").css("display" , "block");
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs")
or die(mysql_error());
?>
<div id="job-container">
<?php
Print "";
while($info = mysql_fetch_array( $data ))
{
Print "<div class='job-post'>";
Print "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
Print "<h3 id='view-job'>View Job:</h3> <div id='job-details'>".$info['jobdesc'] . " </div>";
Print "</div>";
}
?>
</div><!--//END job-container-->
Assign the classNames instead of id's
Then use the this context to select your div which will only search for the one in the context and not all the divs
$("h3.view-job").on('click',function() {
$(this).next("div.job-details").css("display" , "block");
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-details{display:none;}
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
// Please hide this class on CSS
// $("div.job-details").css("display" , "none");
$("h3.view-job").click(function() {
// you ned to use this keyword
// it is very important when you use javascript or jquery
// this keyword only pick element on which you click
$(this).parent().find(".job-details").show();
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs")
or die(mysql_error());
?>
<div id="job-container">
<?php
// First of all Please use echo instead of Print
echo "";
while($info = mysql_fetch_array( $data ))
{
echo "<div class='job-post'>";
echo "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
// you can't use id multiple time in a same page so instead of id use Class
// if you want to use id then you have to generate uniq id
// check below I generate id --> I don't know your database field that's why I used jobId
echo "<h3 class='view-job' id='job".$info['jobId']."'>View Job:</h3> <div class='job-details'>".$info['jobdesc'] . " </div>";
echo "</div>";
}
?>
</div><!--//END job-container-->
This should do what you want (tested okay). Just replace your mysql login info and the example should work.
I completed your job-details div (it was missing the data from php), but what you were really looking for is the jQuery code.
When an <h3> tag whose id begins with the characters view-job is clicked, the jQuery click event handler will:
re-hide all divs whose id starts with the chars job-details
display the next div in the DOM tree
CODE:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div[id^='job-details']").css("display" , "none");
$('h3[id^="view-job"]').click(function() {
$("div[id^='job-details']").hide(500);
$(this).next('div').show(500);
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs") or die(mysql_error());
?>
<div id="job-container">
<?php
echo "<br>";
while($info = mysql_fetch_assoc( $data )) {
echo "<div class='job-post'>";
echo "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
echo "<h3>View Job:</h3> <div id='job-details'>".$info['jobdetails']."</div>";
echo "</div>";
}
?>
</div><!--//END job-container-->

PHP AJAX Load More

Hi i have a script that when user click load more button, ajax will request new content and
display to users, but i have issue where if all the content has been loaded and if user click load more button it cause bug and repeatedly show multiple load more button.Following is my code, need to know how to resolve this. If there is no content to load the button need to be disabled.Thanks guys !!
ajax_more.php
<?php
include("config.php");
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$result=mysql_query("select * from messages where mes_id<'$lastmsg' limit 3");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
<?php
}
?>
loadmore.php
<?php
include('config.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Twitter Style load more results.</title>
<link href="frame.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
</script>
<style>
body
{
font-family:Arial, 'Helvetica', sans-serif;
color:#000;
font-size:15px;
}
a { text-decoration:none; color:#0066CC}
a:hover { text-decoration:underline; color:#0066cc }
*
{ margin:0px; padding:0px }
ol.timeline
{ list-style:none}ol.timeline li{ position:relative;border-bottom:1px #dedede dashed; padding:8px; }ol.timeline li:first-child{}
.morebox
{
font-weight:bold;
color:#333333;
text-align:center;
border:solid 1px #333333;
padding:8px;
margin-top:8px;
margin-bottom:8px;
-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
.morebox a{ color:#333333; text-decoration:none}
.morebox a:hover{ color:#333333; text-decoration:none}
#container{margin-left:60px; width:580px }
</style>
</head>
<body>
<div style="padding:4px; margin-bottom:10px; border-bottom:solid 1px #333333; "><h3>Tutorial Link Click Here</h3></div>
<div id='container'>
<ol class="timeline" id="updates">
<?php
$sql=mysql_query("select * from messages LIMIT 3");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
?>
<li>
<?php echo $message; ?>
</li>
<?php } ?>
</ol>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
</div>
</body>
</html>
<?php
include("config.php");
$count=0;
$done=false;
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$result=mysql_query("select * from messages where mes_id<'$lastmsg' limit 3");
$check=mysql_result(mysql_query("select mes_id from messages ORDER BY mes_id ASC limit 1"));
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
if($row['mes_id']==$check){$done=true;}
$count++;
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
if($count>0 && !$done){
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
<?php
}
}
?>
Explanation: You were unconditionally outputting the more link. With the changes made, the script checks if more than 0 messages have been loaded from the table before outputting a more link. I have also updated it to check if the current batch is the last and not output the more div if it is.
try this code;
$.ajax({
**$("#load_buton").attr("disabled","disabled");**
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").append(html);
$("#more"+ID).remove();
**$("#load_buton").removeAttr("disabled");**
});
In the php section, only display the More button if your returned row size count is greater than 0
Edge cases:
If your database table size increases by n rows, you will repeat n
records each time you hit More
As above, but if records are removed, you will miss out records
Security issues:
SQL injection by sending "0'; truncate messages;--" in the last message post field
Cross site scripting - if users can submit messages with HTML/JavaScript they will be returned in the content without escaping.
In both cases above, use. MySQL escape string ( http://php.net/manual/en/function.mysql-real-escape-string.php ), or use mysqli, and use htmlentities ( http://php.net/manual/en/function.htmlentities.php )

Categories