AJAX, PHP & MYSQL- Limit Data Selection and Offset - php

Okay so here my question i have a blog and i want to show user on first page only 5 posts so i execute this query
mysql_query("select * from posts LIMIT 5");
And then after showing 5 post i made a button named as: Show more posts
when user click on that button another PHP file(loadmoreposts.php) executed in which i execute this query
mysql_query("select * from posts LIMIT 5 OFFSET 5");
but i want to show user 5 post every time it clicks on that button so i make this loop in my PHP script loadmoreposts.php
include('dbConnectClass.php');
$connect = new doConnect();
$beforequery = mysql_query('select * from posts ORDER BY id DESC LIMIT 1;');
if (mysql_num_rows($beforequery) > 0) {
$max_public_id = mysql_fetch_row($beforequery);
$lastid = $max_public_id[0]; //Here it is
}else{
$lastid = "[0]";
}
echo "Last ID $lastid<br />";
$m=5;
for($n=5; $n<=15; $n++):
$afterQuery = mysql_query("select * from posts LIMIT $m OFFSET $m");
$m = $m+5;
$result = "";
while($row = mysql_fetch_assoc($afterQuery)){
$result .= "<div class='cd-timeline-block'>";
$result .="<div class='cd-timeline-img cd-warning'>";
$result .=" <i class='fa fa-pencil-square-o'></i>";
$result .="</div>";
$result .="<div class='cd-timeline-content'>";
$result .= "<h2>{$row['title']}</h2>
<p>{$row['content']}</p>
<img src='{$row['imagesrc']}' alt=''>
<br />
<span style='font-size:85%;'' class='label label-primary'>{$row['category']}</span>
</div>
</div>";
}
echo $result;
endfor;
Let me explain what i did in this script, first i connect to database by a class then i grab last id of my post(last updated post) by running $beforequery and then one more time i execute another query named as $afterquery and then i get my results
but i don't want to show all my posts only in one click i want to show them 5 at a time when user click on that button like first five are already showing but clicking on button will show 5 more then after clicking again it will show the next 5 posts.
this script is then grabbed by this AJAX script:
var loadmoreposts = function () {
$.post('assets/includes/fetchMoreRows.php').done(function( data ) {
$('#displaymoreposts').html(data);
});
}
This loadmoreposts(); fuction is running in onload="loadmoreposts();"body tag
Any Suggestions and help will be appreciated :)
============================
*EDITED**
===========================
I removed the loop and added this but not working
include('dbConnectClass.php');
$connect = new doConnect();
$m = $_POST['offset'];
$afterQuery = mysql_query("select * from posts LIMIT 5 OFFSET $m");
$result = "";
while($row = mysql_fetch_assoc($afterQuery)){
$result .= "<div class='cd-timeline-block'>";
$result .="<div class='cd-timeline-img cd-warning'>";
$result .=" <i class='fa fa-pencil-square-o'></i>";
$result .="</div>";
$result .="<div class='cd-timeline-content'>";
$result .= "<h2>{$row['title']}</h2>
<p>{$row['content']}</p>
<img src='{$row['imagesrc']}' alt=''>
<br />
<span style='font-size:85%;'' class='label label-primary'>{$row['category']}</span>
</div>
</div>" ;
// $result .= "<tr><td> {$row['name']}</td>"."<td> {$row['password']}</td></tr></p>";
}
echo $result;
and JS/AJAX script is now this
var offsetValue = 0;
var loadmoreposts = function () {
$.post( 'assets/includes/fetchMoreRows.php', { offset: offsetValue} ).done(function( data ) {
$('#displaymoreposts').html(data);
offsetValue += 5;
});
}

Your AJAX script needs to send the current value for OFFSET, starting with 0. Everytime you click on your Show more posts link, it increases the value by 5.
So you should change your AJAX script to:
var offsetValue = 0;
var loadmoreposts = function () {
$.post( 'assets/includes/fetchMoreRows.php', { offset: offsetValue} ).done(function( data ) {
$('#displaymoreposts').html(data);
offsetValue += 5;
});
}
In your PHP script, you can grab the offset value like that:
$m = $_POST['offset'];
Also don't increase LIMIT. Change your query to:
mysql_query("select * from posts LIMIT 5 OFFSET $m");
If you increase LIMIT, the script will return +5 more posts everytime.
Hope that helps.

You can simply send the offset in the AJAX request, and use that offset in your query, here are simple steps:
Load first 5 posts, make the value sent by AJAX "load more" button be 5
When "load more" button is clicked, take the value sent (in our case 5) and insert it in the query (hopefully using prepared statements for security) and retrieve next 5 posts and send back the 5 posts and the new value for "load more" button which is now 10 (can be calculated by adding 5 to the value you got from the AJAX request
repeat, by sending 10 when the "load more" button is clicked, retrieving next 5 posts starting at number/offset 10, returning the 5 posts and the new value for the "load more" button which is 15 (10 + 5)
and so on ...

Try this..
//variable to hold the offset
var offSet = 5; //initial value
//send this in your post request
$.post('url', {aOffset : offset }, function(returnedData) {
// do something here
//update the offset value
offset+=5; });

Related

PHP loading items from the database into a div on load more button click

I have a main.php page where I have a while loop that displays the first 10 items from the database. I want to load the next 10 items once a load more button is clicked.
$res = mysql_query("SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 10");
if($res && mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$id = $row['id'];
?>
<div class="main_page">
item id <?php echo $id; ?>
</div>
<button class="load_more">Load More</button>
....
What is a good way of doing this? Any help is much appreciated!
UPDATE:
right now i have this script for the load more button:
<script type="text/javascript">
$(document).ready(function(){
$(".load_more").click(function (){
$('.load_more').html('<img src="images/ajax-loader.gif" />');
$.ajax({
url: "loadmore.php?id=" + $(".ad_display:last").attr("id"),
success: function(html){
if(html){
$(".main_page").append(html);
$('.load_more').html('Load More');
}else{
$('.load_more').replaceWith('No posts');
}
}
});
});
});
</script>
after the form of the filters is submitted, the url looks somewhat like this:
index.php?search=&category=0&ad_order=1
how do I pass on the search (even if empty), ad_order, and category value to the loadmore.php?
limit 0, 10 will display the first 10 items from your query. limit 20,10 will display 10 items starting with the 20th item (counting from zero). You can pass the page number or the number of items retrieved up to now in a parameter when you call the page that does the query. This will involve either reloading the current page with a different start index in limit, or issuing an ajax query that lets you load more items without reloading the page.
Apart from the answer posted by Octern, not sure what you want to achieve for your second question but try:
<script type="text/javascript">
//saving the GET variables
ad = <?php echo $_GET['ad_order']; ?>
catg = <?php echo $_GET['category']; ?>
search = <?php echo $_GET['search']; ?>
//default value of record to start from
rec = 0;
$(document).ready(function(){
$(".load_more").click(function (){
$('.load_more').html('<img src="images/ajax-loader.gif" />');
$.ajax({
//passing them here
//URL updated to pass rec
url: "loadmore.php?id=" + $(".ad_display:last").attr("id")+"&search="+search+"&category="+catg+"&ad_order="+ad+"&rec="+rec,
success: function(html){
//updating counter to start from record
rec += 10;
if(html){
$(".main_page").append(html);
$('.load_more').html('Load More');
}else{
$('.load_more').replaceWith('No posts');
}
}
});
});
});
</script>
In your loadmore.php you need to relevant code to fetch the above $_GET values
Your query will be something like:
$res = mysql_query("SELECT * FROM classifieds WHERE date < '".mysql_real_escape_string($_GET['id'])."' AND search = '".$_GET['search']."' AND category = '".$_GET['category']."' AND ad_order = '".$_GET['ad_order']."' ORDER BY date DESC LIMIT '".$_GET['rec']."',10");
So everytime you click on the load_more, the limit will change as LIMIT 0,10 -> LIMIT 10,10 -> LIMIT 20,10 etc.

Show more result from database with jQuery and AJAX

I'm trying to create news block with AJAX in my template. so i wrote a simple code, in HTML Part:
Show Posts
<div id="result"></div>
jQuery Part:
function ShowPost(){
$.post(dir + 'engine/ajax/posts.php', {action:"showpost"},
function(data) {
$("#result").html(data);
});
};
PHP Part:
if ($_POST['action'] == "showpost") {
$db->query( "SELECT title FROM post LIMIT 0,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Question is, how i can get more result after first click? for example, after first click on Show Posts link, i can show the 5 news from database. after second click on Show Posts link i need to show 6 to 10 news, in third click get result from 11 to 15 and continue ...
i hope you understand my question.
Based on your implementation you need to keep track how many items you have shown and pass the page number in. For example:
jQuery Part:
var pageNumber = 0;
function ShowPost() {
pageNumber++;
$.post(dir+ 'engine/ajax/posts.php', {action:"showpost", pageNum: pageNumber},
function(data) {
$("#result").html(data);
});
};
Disclaimer: I m not a PHP developer so please treat teh code below as pseudo-code.
PHP Part:
if ($_POST['action'] == "showpost") {
var pageSize = 5;
var pageNumber = $_POST['pageNumber'];
var from = (pageNumber - 1) * pageSize;
var to = pageNumber * pageSize;
$db->query( "SELECT title FROM post LIMIT " + from + "," + pageSize);
while ( $row = $db->get_row()) { echo $row['title']."<br>"; }
}
Just implement the pagination limit in ur query
var offset = -5;
function ShowPost(){
offset = offset + 5;
$.post(dir + 'engine/ajax/posts.php', {action:"showpost",offset:offset},
function(data) {
$("#result").html(data);
});
};
PHP part
if ($_POST['action'] == "showpost") {
$vOffset = $_POST['offset'];
$db->query( "SELECT title FROM post LIMIT $vOffset,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Take a hidden field in html and update it's value after every success call and when next time you call for next record send that value in post.
<input type="hidden" name="limit" value="5">
Show Posts
<div id="result"></div>

show more button with PHP Mysql

I have a "show more" button to display 5 of last entries into database, with initial display of 1 record, like to change the initial variable to 3 results shown, here's my code:
$latest_entry_qry="SELECT *
FROM cityres
ORDER BY id DESC
LIMIT 0 , 5";
$latest_entry=mysql_query($latest_entry_qry);
?>
<div id="just-head"> <b>Recently Added:</b></div>
<div id="just-added">
<?
$modu = 1;
while($latest_entry_row=mysql_fetch_array($latest_entry))
{
if($modu%5 == 1)
$clsText = "";
else
$clsText = " class='show_more' style='display:none' ";
Here is a guess as your while loop is incomplete. I am assuming at the end there is a -
$modu++;
since you are checking $modu%5 == 1 every time in the while loop. if so, then you could just change it from
if($modu%5 == 1)
to
if($modu <=3)
Also, make note of #Daedalus comment about no longer using mysql_* functions

jquery ajax php: page content not refrshing!

i am trying to implement pagination. A set of 9 products are displayed at a time. then upon clicking on a "View More" button, the content of a div should refresh by AJAX and show the next set of 9 products..here's the php code
if(!isset($_SESSION['current'])){
$query = "SELECT MAX(addedon) AS addedon FROM tags";
$result = mysql_query($query);
report($result);
$dated = mysql_fetch_assoc($result);
$recent = $dated['addedon'];
$_SESSION['current'] = $recent;
}
$query = "SELECT id, addedon
FROM tags
WHERE addedon <= '{$_SESSION['current']}'
ORDER BY addedon DESC
LIMIT 9
";
$result = mysql_query($query);
report($result);
while($row = mysql_fetch_assoc($result)){
$_SESSION['current'] = $row['addedon'];
$id = $row['id'];
$query = "SELECT name, image, cost
FROM tags, stock
WHERE tags.id={$id} AND stock.tagid = tags.id
";
$result1 = mysql_query($query);
report($result1);
$prodInfo = mysql_fetch_assoc($result1);
$pname = $prodInfo['name'];
$pimg = $prodInfo['image']; //the path to the actual image
$pcost = $prodInfo['cost'];
echo "<div class=\"oneproduct\">";
echo "<h3>{$pname}</h3><br />";
echo "<img src=\"{$pimg}\" height=\"{$ht}\" width=\"85px\" alt=\"prodImg\" /><br />";
echo "<span>Rs. {$pcost}</span>";
echo "<input type=\"image\" src=\"images/addcart.png\" class=\"addBtn\" />";
echo "</div>";
}
after all the products would be fetched and displayed, the last product on the page is stored as 'current' variable of SESSION.
problem is: the ajax thing always returns the initial set of 9 products and as soon as i refresh the page, the next set of products are coming..how do i make my link change the content?
The ajax code:
$("#viewMore").bind('click', function(){
$.ajax({
url:'showNineProds.php',
type:'POST',
dataType:'html',
success:function(data){
$("div#nineproducts").html(data);
},
error:function(xhr, status){
alert("Problem");
},
complete:function(xhr, status){
}
});
});
showNineProds.php simply calls a function that has been written above..
The correct way to do this is for the client-side code to specify with parameters to the AJAX call which "page" of records to be fetched. By using a session variable like this, the server has no concept of which records to get at which time. It's always going to return the "next" result. So any time you load that web page, it's going to serve the "next" set of records. There's no way to page backward in the result set.
Basically, you would store in local JavaScript values (or hidden form elements on the page, however you feel comfortable storing a value on the page) the information of the current result set and your AJAX call would send the necessary information to the server to return the requested result set.
For example, you could have a local JavaScript value that says which start record you're seeing and your page size:
startRecord = 1;
pageSize = 10;
Then if you click your "next" button the AJAX call would supply parameters to the server telling it what to fetch:
startRecord + pageSize, pageSize
You'd want to add a little bit of logic to determine if you're on the first or last page to disable "prev" and "next" functionality, of course. And there's a lot more you can do (variable page sizes, filtering and searching, sorting, etc.) but this is the basic gist of it.
You don't seem to be sending back the info from the ajax call. basically yoi might be fetching the values on the DB but don't seem to be sending the data back to the call..
do you echo the result set in some format? I can't see that in the code. in any case you can't access the $session variables from the js... these are accessible server side in php.

Making album-viewer like facebook

I am working on making a album-viewer like facebook.
I have made the "setup", you can see the photo, what album its in and so, now I would like to make the "next" "previous" buttons work.
I have seen them using preloading while viewing a current, and i wish to accomplish something like that.
But first of all, how can I make the "next"? What are the procedure to make the "next" work.
With this I mean how should I code it, so it knows which picture is next? I would like to sort it from the date(order by date), so the next should be newer than the current date, and previous older than the current date.
My database looks like this:
album
id uID title
album_photos
id aID uID photo date
aID holds the id of the album(album ID), uID holds the id of the user(userID).
I also want to make use of javascript too. Make an ajax request, instead of refreshing whole page.
So my question is:
What is the procedure of making next/prev button, if I would like to make it work after date DESC, how does the javascript look like? An ajax request to file.php, that are grabbing the latest image from the database and then on success it replace the current photo and show it? What about the adressbar, in facebook the adressbar changes align with loading new photo.
Any well explained answer for procedure of making this, will accept the answer
This here will load images from the database using ajax (next/previous). Also includes guides and a preloader (hosted here http://www.preloaders.net/). Let me know if you have any questions.
Here you go. these are 3 files
index.php ...display page
ajax.php ...read database for images
show.php ...loads images
just remember to set host, user, password & databasename in ajax.php
copy & paste these:
1. index.php
<?php
include("ajax.php");
?>
<script type="text/javascript" src="JQUERY/jquery.js"></script>
<script>
var ID = "<?php echo $id; ?>";
var inc = ID + 1;
var dec = ID;
var totalpages = "<?php echo $totalpages + 1; ?>";
$(function(){
$('.loader').hide();
<!-- np = next & prev button functions -->
$('.np').click(function() {
if($(this).attr('id') == "next") {
$(this).attr('push', inc++);
if($(this).attr('push')<totalpages) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
dec = inc - 2;
$('#images').hide();
}
}
else if($(this).attr('id') == "prev") {
$(this).attr('push', dec--);
if($(this).attr('push')>-1) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
inc = dec + 2;
$('#images').hide();
}
}
});
});
<!-- this function is called after ajax send its request -->
function AjaxFunc(return_value) {
$('#images').html(return_value);
$('.loader').hide();
$('#images').show();
}
</script>
<div id="images">
<!-- loads default numbers of images. whats inside here will change once you click next or prev -->
<?php
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
</div>
<!-- next & previous buttons -->
<a class="np" id="prev" push="<?php echo $id; ?>" href="#">Prev</a>
<a class="np" id="next" push="<?php echo $id + 1; ?>" href="#">Next</a>
<!-- preloader. hidden on start. will show while images load -->
<img class="loader" src="http://www.preloaders.net/generator.php?image=75&speed=5&fore_color=000000&back_color=FFFFFF&size=64x64&transparency=0&reverse=0&orig_colors=0&uncacher=26.066433149389923"/>
2. ajax.php
<?php
//id is tjhe page number. it is 0 by default. while clicking next/prev, this will not change. set it like this: file?id=0
$id = $_GET['id'];
//connect to the databsae
$host="localhost";
$user = "username";
$password = "";
$database = "database_name";
$connect = mysql_connect($host, $user, $password) or die("MySQL Connection Failed");
mysql_select_db($database) or die ("Database Connection Fail");
//set your the limit of images to be displayed
$limit = 5;
//push images into array
$q = mysql_query("SELECT * FROM image_table");
$num = mysql_num_rows($q);
while($r = mysql_fetch_array($q)) {
$imagearray[] = "<img src='"
.$r['IMAGE_URL']
."'/>";
}
//will determine total number of pages based on the limit you set
$totalpages = ceil($num/$limit) - 1;
?>
3. show.php
<?php
include("ajax.php");
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
If you are sorting your photos by date DESC and you got the current photos date do the following:
To find the next photo: Order your photos by date DESC and select the first photo whos date is smaller than the date of the current photo. Fetch only the first one.
To find the prev photo: Order your photos by date ASC and select the first photo whos date is greater than the date of the current photo. Fetch only the first one.
Construct the SQL-Statements for this by yourself.

Categories