I am trying to create an Ajax pagination system to display my XML API (SOAP) results.
I have a liittle example that show me how to fetch the reults from a mysql db. But I need to fetch my rezults from XML API & Database.
The example:
jQuery:
$(document).ready(function() {
$("#results" ).load( "fetch_pages.php"); //load initial records
//executes code below when user click on pagination links
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
$(".loading-div").show(); //show loading element
var page = $(this).attr("data-page"); //get page number from link
$("#results").load("fetch_pages.php",{"page":page}, function(){ //get content from PHP page
$(".loading-div").hide(); //once done, hide loading element
});
});
});
PHP
//get total number of records from database for pagination
$results = $mysqli_conn->query("SELECT COUNT(*) FROM paginate");
$get_total_rows = $results->fetch_row(); //hold total records in variable
//break records into pages
$total_pages = ceil($get_total_rows[0]/$item_per_page);
//get starting position to fetch the records
$page_position = (($page_number-1) * $item_per_page);
//SQL query that will fetch group of records depending on starting position and item per page. See SQL LIMIT clause
$results = $mysqli_conn->query("SELECT id, name, message FROM paginate ORDER BY id ASC LIMIT $page_position, $item_per_page");
//Display records fetched from database.
echo '<ul class="contents">';
while($row = $results->fetch_assoc()) {
echo '<li>';
echo $row["id"]. '. <strong>' .$row["name"].'</strong> — '.$row["message"];
echo '</li>';
}
echo '</ul>';
echo '<div align="center">';
/* We call the pagination function here to generate Pagination link for us.
As you can see I have passed several parameters to the function. */
echo paginate_function($item_per_page, $page_number, $get_total_rows[0], $total_pages);
echo '</div>';
}
HTML:
<div class="loading-div"><img src="ajax-loader.gif" ></div>
<div id="results"><!-- content will be loaded here --></div>
I have:
Variables from XML API: $boardType[n] , $hotelPrices[n],
$availHotels[n]->rooms[n]->roomCategory;
Variables from MYSQL: $hotelName[n], $hotelAddress[n],
$img[n][x] etc..
The code built so far is:
//get total number of records from database for pagination
$results = count($availHotels);
$get_total_rows = $results->fetch_row(); //hold total records in variable
//break records into pages
$total_pages = ceil($get_total_rows[0]/$item_per_page);
//get starting position to fetch the records
$page_position = (($page_number-1) * $item_per_page);
//SQL query that will fetch group of records depending on starting position and item per page. See SQL LIMIT clause
$results = mysql_query("SELECT , HotelAddress, HotelImages, Destination, StarRating FROM HotelList where HotelCode= '$hotelc' ORDER BY id ASC LIMIT $page_position, $item_per_page" , $link);
//Display records fetched from database.
echo '<ul class="contents">';
while($row = $results->fetch_assoc()) {
echo '<li>';
echo $row["HotelName"]. '. <strong>' .$row["HotelAddress"].'</strong> — '.$row["Destination"];
echo '</li>';
}
echo '</ul>';
echo '<div align="center">';
/* We call the pagination function here to generate Pagination link for us.
As you can see I have passed several parameters to the function. */
echo paginate_function($item_per_page, $page_number, $get_total_rows[0], $total_pages);
echo '</div>';
}
Page returns empty
Related
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; });
I trying to implement ajax pagination for image thumb gallery but seems I can understand this well and I miss something.
So this is my html
<div class="row">
<div class="loading-div"><img src="ajax-loader.gif" ></div>
<div id="results"></div>
</div>
and in the head of the page
<script type="text/javascript">
$(document).ready(function() {
$("#results" ).load( "fetch_pages.php"); //load initial records
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
$(".loading-div").show(); //show loading element
var page = $(this).attr("data-page"); //get page number from link
$("#results").load("fetch_pages.php",{"page":page}, function(){ //get content from PHP page
$(".loading-div").hide(); //once done, hide loading element
});
});
});
</script>
And the php part
if(isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//continue only if $_POST is set and it is a Ajax request
if(isset($_GET['album_id']) && is_numeric($_GET['album_id'])){
$album_id = $_GET['album_id'];
include("config.inc.php"); //include config file
//Get page number from Ajax POST
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1; //if there's no page number, set it to 1
}
//get total number of records from database for pagination
$results = $mysqli_conn->query("SELECT COUNT(*) FROM images");
$get_total_rows = $results->fetch_row(); //hold total records in variable
//break records into pages
$total_pages = ceil($get_total_rows[0]/$item_per_page);
//get starting position to fetch the records
$page_position = (($page_number-1) * $item_per_page);
//SQL query that will fetch group of records depending on starting position and item per page. See SQL LIMIT clause
$results = $mysqli_conn->query("SELECT * FROM images WHERE image_album = '$album_id' ORDER BY image_id ASC LIMIT $page_position, $item_per_page");
//Display records fetched from database.
while($row = $results->fetch_assoc()) {
echo '<div class="col-md-4 col-ms-6">
<div class="g-item">
<img src="../images/gallery/thumb/'.$row['image_name'].'">
<a data-rel="lightbox" class="overlay" href="../images/gallery/thumb/'.$row['image_name'].'">
<span>+</span>
</a>
</div> <!-- /.g-item -->
</div> <!-- /.col-md-4 -->';
}
echo '<div align="center">';
echo paginate_function($item_per_page, $page_number, $get_total_rows[0], $total_pages);
echo '</div>';
}
} else { echo "no items in this album"; }
What I try to achieve is when user click on category ( which already is working fine ) to load new page with the images from this category (album) and then there are few thumbs and pagination.
When I remove the part with $_GET is work but I need to get album_id in order to show only those images. Here is the button on the index page
gallery.php?album_id='.$row['album_id'].'
Tutorial that I follow is from here
There is no errors and no images on the page..
Well you do not send the album_id to your script
$("#results").load("fetch_pages.php",{"page":page},
You only add the page which should be loaded not the album id.
Second you send the data via post. $_GET is always empty in post requests.
I am using the following code for pagination with ajax and php.
fetch_pages.php
<?php
include("config.inc.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
//$results = mysqli_query($connecDB,"SELECT id,name,message FROM paginate ORDER BY id ASC LIMIT $position, $item_per_page");
$results=array(array('id'=>1,'name'=>'joe','age'=>'22','job'=>'dev'),array('id'=>2,'name'=>'g','age'=>'21','job'=>'se'),array('id'=>3,'name'=>'gt','age'=>'21','job'=>'se'));
$output = array_slice($results, 0,1);
//output results from database
echo '<ul class="page_result">';
//while($row = mysqli_fetch_array($results))
foreach ($output as $row)
{
echo '<li id="item_'.$row["name"].'">'.$row["age"].'. <span class="page_name">'.$row["job"].'</span><span class="page_message">'.$row["name"].'</span></li>';
}
echo '</ul>';
?>
index.php
<?php
include("config.inc.php");
//$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM paginate");
$results=array(array('id'=>1,'name'=>'joe','age'=>'22','job'=>'dev'),array('id'=>2,'name'=>'g','age'=>'21','job'=>'se'),array('id'=>3,'name'=>'gt','age'=>'21','job'=>'se'));
//$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
//$pages = ceil($get_total_rows[0]/$item_per_page);
$pages = ceil(3/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Pagination</title>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="results"></div>
<?php echo $pagination; ?>
</body>
</html>
I want the data source for this to be an array defined in the code, not a mysql database therefore you will see $results=array(array('name'=>'gowrie','age'=>'22','job'=>'dev'),array('name'=>'g','age'=>'21','job'=>'se')); instead of a mysql query.
In fetchespages.php there should be a query $results = mysqli_query($connecDB,"SELECT id,name,message FROM paginate ORDER BY id ASC LIMIT $position, $item_per_page");, that would limit the result for the page, however I replaced it with $results=array(array('name'=>'joe','age'=>'22','job'=>'dev'),array('name'=>'g','age'=>'21','job'=>'se'));
The page shows the correct number of pagination links, but when I click them, they don't work, it just keeps loading. I'm not sure if it's a problem with my ajax in index.php or the way I attempt to limit results in the array in fetch_pages.php, ie $output = array_slice($results, 0,1); WHn I click the pagination links, it loads the same thing on the page.
How do I fix this?
Well if you use
$output = array_slice($results, 0,1);
the array is always limited to the first key=>value pair no matter which page link you click. Just like in the sql query, where you use limit and position/items per page, you'll have to do the same with your slice function. so it becomes something like
$output = array_slice($results, $position, $items_per_page);
Hope this helps
I'm using this while statement to show all contents of database...
$sql = mysql_query("SELECT id,question,date,user,numberofcomments,body,locked FROM questions ORDER BY id DESC");
while($row=mysql_fetch_assoc($sql)) {
echo '<div class="comment">';
echo '<div class="leftpart">';
echo "<div class='date'><img src='../assets/icons/Time-info.png'> ".ago($row['date']);
echo "</div><br><img src='../assets/icons/User-Info.png'> ".$row['user'];
echo "<br><img src='../assets/icons/Comments.png'> ".$row[numberofcomments];
echo '</div>';
echo '<div class="rightpart-topic">';
if($row['locked']==1) { echo '<img src="../assets/icons/Lock.png" /> ';
}
echo ''.$row['question'].'';
echo '<br>'.substr($row['body'],0,70).'...';
echo '</div>';
echo '</div>';
}
I want to show only 10 rows then have links to show the rest (as in page 1,2,3,4, last type thing). How would I go about doing that? It would help if you could also explain your code as it would be greatly appreciated. It helps my learning process.
Thanks!
You need to do a LIMIT in your query using some sort of passed $_GET variable.
$start=0;
$limit = 10;
$page = (isset($_GET['page']) ? : 0));
$start = $page * $limit;
$sql = mysql_query("SELECT id,question,date,user,numberofcomments,body,locked FROM questions ORDER BY id DESC LIMIT {$start},{$limit}");
Should be pretty self explanatory.
If there is not page variable set then you are viewing page 0, or the first 10 results of your database query. If page = 1 then you are going to be viewing $page (value=1) * $limit (10) = $start (now value of 10), which will give you results 10-20 or page 1. etc.
So provide your user a button which can link them to a hard paginated link, or do it ajax.
Each url will need to be like so:
http://wwww.yoursite.com/somepage.php?page=1
Efficiency aside, you could simply set a counter and check if it value Is greater than 10 during the loop. If so, add a 'hidden' class to the parent div. That class would use display:none;
I am trying to figure out how I can update my sql query dynamically.
On the main page, I have a pagination script that counts how many pages there will be:
<?php
function generate_pagination($sql) {
include_once('config.php');
$per_page = 3;
//Calculating no of pages
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page);
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li class="page_numbers" id="'.$i.'">'.$i.'</li>';
}
}
?>
I then have in the body of the same page this line of code to populate the page numbers:
<?php generate_pagination("SELECT * FROM explore WHERE category='marketing'"); ?>
So, that line is displaying the necessary amount of page numbers to be displayed for just the 'marketing' category.
The problem that I am having is with that single line of code. I want to make the category dynamic, so instead of it being hardcoded to 'marketing' I would like jquery to get the id of an element and place it in.
The element would be this link that I have on the same page:
Marketing
So, when the user clicks that link, I am trying to place the id of the link in the category section of the query using jquery.
I hope that made sense, and if anyone can assist me on this that would be great.
First, the PHP side:
<?php
function generate_pagination($sql) {
include_once('config.php');
$per_page = 3;
//Calculating no of pages
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page);
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li class="page_numbers" id="'.$i.'">'.$i.'</li>';
}
}
?>
<?php generate_pagination("SELECT * FROM explore WHERE category='" . mysql_real_escape_string ( $_POST ['category'] ) . "'"); ?>
Then in your jquery post:
$("a.category").click(function() {
$.post("test.php", { category: $(this).attr("id") },
function(data){
//Load your results into the page
});
});
On click we take the ID, pass it to the server as a post variable category, then on the server, grab it, escape it properly for security, and use that query. Load your results the same way you are now, that part doesn't change.