Ajax search and pagination - php

I have this AJAX pagination code.
$('document').ready(function() {
$("#pagination a").trigger('click'); // When page is loaded we trigger a click
});
$('#pagination, #searchButton').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
e.preventDefault();
var page = this.id; // Page number is the id of the 'a' element
var pagination = ''; // Init pagination
$('#articleArea').html('<img src="images/ajax-loader.gif" alt="" />'); // Display a processing icon
var data = {term: term, page: page, per_page: 9}; // Create JSON which will be sent via Ajax
// We set up the per_page var at 4. You may change to any number you need.
$.ajax({ // jQuery Ajax
type: 'POST',
url: 'includes/fetch-pages.php', // URL to the PHP file which will insert new value in the database
data: data, // We send the data string
dataType: 'json', // Json format
timeout: 3000,
success: function(data) {
$('#articleArea').html(data.articleList); // We update the page with the event list
console.log(data.num);
// Pagination system
if (page == 1) pagination += '<div class="cell_disabled"><span>Primero</span></div><div class="cell_disabled"><span>Anterior</span></div>';
else pagination += '<div class="cell">Primero</div><div class="cell">Anterior</span></div>';
for (var i=parseInt(page)-3; i<=parseInt(page)+3; i++) {
if (i >= 1 && i <= data.numPage) {
pagination += '<div';
if (i == page) pagination += ' class="cell_active"><span>' + i + '</span>';
else pagination += ' class="cell">' + i + '';
pagination += '</div>';
}
}
if (page == data.numPage) pagination += '<div class="cell_disabled"><span>Siguiente</span></div><div class="cell_disabled"><span>Último</span></div>';
else pagination += '<div class="cell">Siguiente</div><div class="cell">Último</span></div>';
$('#pagination').html(pagination); // We update the pagination DIV
},
error: function() {
}
});
return false;
});
Now I want to add a search form:
<form class="form-inline col-xs-12 col-sm-5 col-md-4 hidden-xs" id="searchFormTop">
<div class="row buscar">
<div class="form-group col-xs-9">
<input type="text" placeholder="" class="form-control" name="searchTerm" id="searchTerm" value="test">
</div>
<button type= "submit" class="btn col-xs-3" id="searchButton"> BUSCAR </button>
</div>
</form>
How can I get the value from the form and pass it to the AJAX call? I'm trying to add another event to trigger the ajax call when the form in submited and then get the search term value using val(), but I cannot make in work.
$('document').ready(function() {
$("#pagination a").trigger('click'); // When page is loaded we trigger a click
});
$('#pagination, #searchFormTop').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
e.preventDefault();
var page = this.id; // Page number is the id of the 'a' element
var pagination = ''; // Init pagination
var term = $('#searchTerm').val();
The PHP code processing the request is:
$page = $_POST['page']; // Current page number
$per_page = $_POST['per_page']; // Articles per page
if ($page != 1) $start = ($page-1) * $per_page;
else $start=0;
$today = date('Y-m-d');
$term = $_POST['searchTerm']; // Current page number
// Select items list from $start.
// An item might have multiple categories. A regular join query will create a row for each category
//so that the event will be displayed as many times as categories it has.
//To group all the caegories in one single result, we can use GROUP_CONCAT and then, GROUP BY
$sql = "SELECT *, events.name AS event_name, -- THIS WILL the defferesnt categories on on eevent
GROUP_CONCAT(DISTINCT catevent.cat_id) as cats,
GROUP_CONCAT(DISTINCT categories.name SEPARATOR ', ') as cat_names
FROM events
LEFT JOIN catevent
ON catevent.event_id=events.event_id
LEFT JOIN categories
ON catevent.cat_id=categories.id
LEFT JOIN images
ON images.item_id=events.event_id
WHERE categories.parent_cat != 0
AND publish=1 AND images.item_type_id=1 AND images.img_name NOT LIKE '%sm%' -- We want to get only the name of the regular img for each event
AND final_date >= '$today'
GROUP BY events.event_id -- Needed to display all the events
ORDER BY events.initial_date ASC, events.initial_date DESC, events.name ASC
LIMIT $start, $per_page";
$select=$pdo->query($sql);
$select->setFetchMode(PDO::FETCH_OBJ);
$results = $select->fetchAll();
// Total number of articles in the database
$numArticles = $pdo->query("SELECT count(event_id) FROM events WHERE publish=1 AND final_date >= '$today'")->fetch(PDO::FETCH_NUM);
$numPage = ceil($numArticles[0] / $per_page); // Total number of page
// We build the article list
$articleList = '';
foreach( $results as $result) {
//Get final month, year, and day from date stored in db
$date_from_db=test_output($result->final_date);
$time=strtotime($date_from_db);
$year= date('Y', $time);
$year_short= substr($year,2);
$month=date('n', $time);
$day=date('j', $time);
//Get initial month, year, and day from date stored in db
$date_from_db_i=test_output($result->initial_date);
$time_i=strtotime($date_from_db_i);
$year_i= date('Y', $time_i);
$year_short_i= substr($year_i,2);
$month_i=date('n', $time_i);
$day_i=date('j', $time_i);
//get the sm image name
$lg_image=test_output($result->img_name);
$images_names=get_img_names($lg_image);
$img_sm= $images_names['regular_sm'];
//default event slug
$event_slug=test_output($result->slug);
if (empty($result->slug)||$result->slug=="default" ){
$slug=$result->event_id;
}
//get parent cat name
$parent_cat_id=test_output($result->parent_cat);
$parent_cat_name=cat_name($parent_cat_id);
//if there are several cats for one event, display them
if (isset($result->cat_names)){
$subcat=test_output($result->cat_names);
}else{
$subcat=test_output($result->name);
}
//$articleList .= '<div class="well well-sm">' . $result->id . '. <b>' . $result->title . '</b><p>' . test_output($result->description) . '</p></div>';
include('event-item-agenda.php');
}
// We send back the total number of page and the article list
$dataBack = array('numPage' => $numPage, 'articleList' => $articleList, 'num'=>$numArticles, 'term'=>$term);
$dataBack = json_encode($dataBack);
echo $dataBack;
Maybe, you guys, can help me see what I'm doing wrong.
Thanks in advance
Sonia

Related

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.

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>

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