PHP Ajax pagination array not working - php

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

Related

Pagination with SQL Server does not return the correct results

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pagination</title>
</head>
<body>
<?php
// define how many results you want per page
$results_per_page = 3;
// find out the number of results stored in database
$AllRows = count($sql->query("SELECT * FROM $dbs[WEB2].._WebsiteNews")->fetchAll());
// determine number of total pages available
$number_of_pages = ceil($AllRows/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['news'])) {
$page = 1;
} else {
$page = $_GET['news'];
}
// determine the sql LIMIT starting number for the results on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;
// retrieve selected results from database and display them on page
$PlayersQuery = "SELECT * FROM $dbs[WEB2].._WebsiteNews ORDER BY No OFFSET $this_page_first_result ROWS FETCH NEXT $results_per_page ROWS ONLY ;";
$query = $sql->Query1($PlayersQuery);
while ($row = $sql->QueryFetchArray($query)) {
echo $row['No'] . ' ' . $row['Title']. '<br>';
}
// display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
echo '' . $page . ' ';
}
?>
</body>
</html>
I have like 7 pages, I only get same result (3 same result every page); no idea what is wrong with it.
I have been searching to make it with SQL Server but all have with MySQL; if someone knows how to make it work, please help me - thanks
MySQL
$PlayersQuery = "SELECT * FROM $dbs[WEB2].._WebsiteNews ORDER BY No LIMIT $this_page_first_result, $results_per_page;";
MSSQL
$PlayersQuery = "SELECT * FROM $dbs[WEB2].._WebsiteNews ORDER BY No
OFFSET $this_page_first_result ROWS
FETCH NEXT $results_per_page ROWS ONLY;
well here the result i get with my code
http://prntscr.com/mouyx1 this first page
http://prntscr.com/mouzc9 2nd page is the same result from first page
also all pages is like that
no idea why ...
every page is show the same result from first page
trying to fix it since 4 hours ^^

Ajax pagination with jQuery & PHP XML API

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

PHP and AJAX pagination

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.

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.

How to update sql query dynamically - jquery

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.

Categories