Combining jQuery Ajax Code Not Working - php

I am trying to amalgamate two ajax functions that use jQuery. Both work perfectly on their own, but I'm having a hell of a time combining the two, and I'm pretty green when it comes to Ajax. I can't figure out what's wrong.
I know this is asking a lot of someone, but I don't know what else to do. I would be extremely grateful for any help, and perhaps an explanation of what I would need to do if I wanted to add more functionality to this code so I don't have to keep bothering you all.
It's an image gallery. The two halves are a combo box to select how many images show per page, and the other is pagination to navigate the pages. I have a feeling it has something to do with the jQuery Ajax data: {page:page, imgs: value} but that might just be part of the problem.
The HTML:
<div id="loading"></div>
<div id="gallery_container">
<ul class="new_arrivals_gallery"></ul>
<div class="pagination"></div>
<form>
<label>Images Number:</label>
<select id="imgNum" name="imgNum">
<option value="12">12</option>
<option value="16">16</option>
<option value="20">20</option>
</select>
</form>
</div>
The JavaScript (jQuery):
function loading_show(){
$('#loading').html("<img src='loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function gallery_show(){
$('#gallery_container').fadeIn('slow');
}
function gallery_hide(){
$('#gallery_container').fadeOut(10);
}
function loadData(page){
loading_show();
gallery_hide();
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: {page:page, imgs: value},
success: function(msg)
{
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#gallery_container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
//Bind the onChange event to Fetch images on combox selection
$("#imgNum").change(function(){
//The combo box
var sel = $(this);
//Selected value
var value = sel.val();
loadData(page);
})
//You should store the current selected option in a cookie
//For the sake of the example i'll set the default permanently to 12
var imgNum_selected = 12;
//set the initial selected option and trigger the event
$("#imgNum [value='"+imgNum_selected+"']")
.prop("selected","selected")
.change();
The PHP:
<?php
if($_GET['page'])
{
$page = 0;
if(isset($_GET['page'])){
$page = (int) $_GET['page'];
}
$cur_page = $page;
$page -= 1;
if((int) $_GET['imgs'] > 0){
$per_page = (int) $_GET['imgs'];
} else {
$per_page = 12;
}
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
include"db.php";
$query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
echo "<ul class='new_arrivals_gallery'>";
while($row = mysql_fetch_assoc($result_pag_data)) {
echo "<li><a href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>";
}
echo "</ul>";
/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
/* ---------------Calculating the starting and endign values for the loop----------------------------------- */
if ($cur_page >= 7) {
$start_loop = $cur_page - 3;
if ($no_of_paginations > $cur_page + 3)
$end_loop = $cur_page + 3;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
$start_loop = $no_of_paginations - 6;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 7)
$end_loop = 7;
else
$end_loop = $no_of_paginations;
}
/* ----------------------------------------------------------------------------------------------------------- */
$msg .= "<div class='pagination'><ul>";
// FOR ENABLING THE FIRST BUTTON
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$msg .= "<li p='1' class='inactive'>First</li>";
}
// FOR ENABLING THE PREVIOUS BUTTON
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$msg .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' style='color:#fff;background-color:#006699;' class='active'>{$i}</li>";
else
$msg .= "<li p='$i' class='active'>{$i}</li>";
}
// TO ENABLE THE NEXT BUTTON
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$msg .= "<li class='inactive'>Next</li>";
}
// TO ENABLE THE END BUTTON
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$msg .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
$goto = "<input type='text' class='goto' size='1' style='margin-top:-1px;margin-left:60px;'/><input type='button' id='go_btn' class='go_button' value='Go'/>";
$total_string = "<span class='total' a='$no_of_paginations'>Page <b>" . $cur_page . "</b> of <b>$no_of_paginations</b></span>";
$msg = $msg . "</ul>" . $goto . $total_string . "</div>"; // Content for pagination
echo $msg;
}
Thank you so much to whomever takes the time to look at this. I know it's a lot, but even if someone tells me what needs to be done, and then I figure out how to do it, I would be extremely grateful.
*I would be willing to include the code of each part before I tried to combine them, if that would help.
ORIGINAL SEPERATE CODE:
Here are both sets of the original code. The goal is to combine them, in other words add code #2 to code #1.
HTML & jQuery #1:
<body>
<div id="loading"></div>
<div id="gallery_container">
<ul class="new_arrivals_gallery"></ul>
<div class="pagination"></div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function gallery_show(){
$('#gallery_container').fadeIn('slow');
}
function gallery_hide(){
$('#gallery_container').fadeOut(10);
}
function loadData(page){
loading_show();
gallery_hide();
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: "page="+page,
success: function(msg)
{
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#gallery_container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
</script>
</body>
PHP #1:
<?php
if($_GET['page'])
{
$page = $_GET['page'];
$cur_page = $page;
$page -= 1;
$per_page = 15;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
include"db.php";
$query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
echo "<ul class='new_arrivals_gallery'>";
while($row = mysql_fetch_assoc($result_pag_data)) {
echo "<li><a href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>";
}
echo "</ul>";
/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM images";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
/* ---------------Calculating the starting and endign values for the loop----------------------------------- */
if ($cur_page >= 7) {
$start_loop = $cur_page - 3;
if ($no_of_paginations > $cur_page + 3)
$end_loop = $cur_page + 3;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
$start_loop = $no_of_paginations - 6;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 7)
$end_loop = 7;
else
$end_loop = $no_of_paginations;
}
/* ----------------------------------------------------------------------------------------------------------- */
$msg .= "<div class='pagination'><ul>";
// FOR ENABLING THE FIRST BUTTON
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$msg .= "<li p='1' class='inactive'>First</li>";
}
// FOR ENABLING THE PREVIOUS BUTTON
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$msg .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' style='color:#fff;background-color:#006699;' class='active'>{$i}</li>";
else
$msg .= "<li p='$i' class='active'>{$i}</li>";
}
// TO ENABLE THE NEXT BUTTON
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$msg .= "<li class='inactive'>Next</li>";
}
// TO ENABLE THE END BUTTON
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$msg .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
$goto = "<input type='text' class='goto' size='1' style='margin-top:-1px;margin-left:60px;'/><input type='button' id='go_btn' class='go_button' value='Go'/>";
$total_string = "<span class='total' a='$no_of_paginations'>Page <b>" . $cur_page . "</b> of <b>$no_of_paginations</b></span>";
$msg = $msg . "</ul>" . $goto . $total_string . "</div>"; // Content for pagination
echo $msg;
}
HTML & jQuery #2:
<body>
<form>
<label>Images Number:</label>
<select id="imgNum" name="imgNum">
<option value="12">12</option>
<option value="16">16</option>
<option value="20">20</option>
</select>
</form>
<div id="imgTray"></div>
<script type="text/javascript" src="js/libs/jquery-1.6.1.min.js"></script>
<script>
//Bind the onChange event to Fetch images on combox selection
$("#imgNum").change(function(){
//The combo box
var sel = $(this);
//Selected value
var value = sel.val();
//Feth the images
$.get("get_images.php",{imgs: value}, function(data){
//Add images to the document
$("#imgTray").html(data);
});
})
//You should store the current selected option in a cookie
//For the sake of the example i'll set the default permanently to 12
var imgNum_selected = 12;
//set the initial selected option and trigger the event
$("#imgNum [value='"+imgNum_selected+"']")
.prop("selected","selected")
.change();
</script>
</body>
PHP #2:
<?php
if((int) $_GET['imgs'] > 0){
$limit = (int) $_GET['imgs'];
} else {
$limit = 12;
}
$curPage = 0;
if(isset($_GET['page'])){
$curPage = (int) $_GET['page'];
}
$mysql_link = mysql_connect("localhost", "root", "root");
mysql_select_db("new_arrivals_imgs") or die("Could not select database");
$query = mysql_query("SELECT `imgURL`,`imgTitle` FROM `images` ".
"ORDER BY `imgDate` DESC LIMIT " . $limit * $curPage . ", $limit") or die(mysql_error());
if(!$query) {
echo "Cannot retrieve information from database.";
} else {
while($row = mysql_fetch_assoc($query)) {
echo "<li><a href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>";
}
}
?>
Thought I should mention: When I change the data: {page:page, imgs: value} back to what it was in code #1: data: "page="+page the images show, and the pagination works. Alas, the combo box is not visible. Any thoughts on that?

I dont think the following code:
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
});
should be in the success function of your ajax call..
The API states that
Whenever an Ajax request completes, jQuery triggers the ajaxComplete event. Any and all handlers that have been registered with the .ajaxComplete() method are executed at this time.
Thus in your case any further ajax requests should fire the ajaxComplete event and call the callback function for the same..
Hope that makes sense.. I have not worked with the ajaxComplete API myself and this is my understanding

Your success callback be just this:
success: function(msg) {
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
}
That way, when you successfully get your HTML (in msg) back from the server, you will show the gallery, hide the loader animation, and stuff the msg HTML into the gallery.
The ajaxComplete function registers an "AJAX is done" handler:
Whenever an Ajax request completes, jQuery triggers the ajaxComplete event. Any and all handlers that have been registered with the .ajaxComplete() method are executed at this time.
But you're not doing any AJAX on #gallery_container, you are doing things to it but it doesn't know that those things originate from AJAX actions. The result is that your success handler does nothing that the user can see.
An error handler might be a good addition as well, then you could move the "hide loader animation" to a complete handler:
success: function(msg) {
gallery_show();
$("#gallery_container").html(msg);
},
error: function(jqXHR, textStatus, errorThrown) {
// Tell the human that something broke.
},
complete: function() {
// This is always called regardless of success or failure.
loading_hide();
}
The complete handler is:
A function to be called when the request finishes (after success and error callbacks are executed).
So that's a good place to put any cleanup that you always want to happen.

Related

PHP - Search with Pagination

So I have these two PHP files products.php and receive.php .
What my problem is I want to use Ajax on displaying the products with search and paginates also. The code below works though but only if I use a GET. Is it possible to submit only the page number and refreshes only the div (where products loop) and not the whole page so that my POST requests (from search values - title, keywords) will still hold? coz if I use GET on pagination, the POST requests are getting empty after clicking the second page.
receive.php
$pdo_sql = 'SELECT * FROM items WHERE item_title LIKE %$keyword% OR keywords LIKE %$keyword% ORDER BY id DESC ';
/*** Pagination Code starts ***/
$per_page_html = '';
$page = 1;
$start=0;
// Get Page Number
if(!empty($_GET["page"])) {
$page = $_GET["page"];
$start=($page-1) * ROW_PER_PAGE;
}
// Adds Limit to Query then Execute
$limit=" LIMIT " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($pdo_sql);
$pagination_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
// Count the total number of rows
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$total_links=ceil($row_count/ROW_PER_PAGE);
$previous_link = $next_link = $page_link = '';
if($total_links > 4)
{
if($page < 5)
{
for($count = 1; $count <= 5; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
else
{
$end_limit = $total_links - 5;
if($page > $end_limit)
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $end_limit; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
else
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $page - 1; $count <= $page + 1; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
}
}
else
{
for($count = 1; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
for($count = 0; $count < count($page_array); $count++)
{
if($page == $page_array[$count])
{
// Current Page = Selected Page
$page_link .= '<a class="paginate_current" href="javascript:void(0)">'.$page_array[$count].'</a>';
$previous_id = $page_array[$count] - 1;
if($previous_id > 0)
{
// Previous Button Enable
$previous_link = '<a class="paginate_prev" href="products.php?page='.$previous_id.'">Previous</a>';
}
else
{
// Previous Button Disabled
$previous_link = '<a class="paginate_prev-disabled" href="javascript:void(0)">Previous</a>';
}
$next_id = $page_array[$count] + 1;
if($next_id > $total_links)
{
// Next Button Disabled
$next_link = '<a class="paginate_next-disabled" href="javascript:void(0)">Next</a>';
}
else
{
// Next Button Enabled
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
}
}
else
{
if($page_array[$count] == '...')
{
// Ellipsis
$page_link .= '<a class="paginate_ellipsis" href="javascript:void(0)">...</a>';
}
else
{
// Pages
$page_link .= '<a class="paginate_pages" href="products.php?page='.$page_array[$count].'">'.$page_array[$count].'</a>';
}
}
}
$per_page_html .= '<div class="text-center paginate">';
$per_page_html .= $previous_link . $page_link . $next_link;
$per_page_html .= '</div>';
}
$query = $pdo_sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$pdo_result = $pdo_statement->fetchAll();
products.php
<div class="row">
<div class="col">
<div class="products_container grid" id="refresh">
<?php
if(!empty($pdo_result)) {
foreach($pdo_result as $pdo_row) {
$id = $pdo_row['id'];
$name = $pdo_row['item_title'];
$img = $pdo_row['item_img'];
$price = $pdo_row['item_price'];
$sold = $pdo_row['item_sold'];
$stocks = $pdo_row['stocks'];
$date = $pdo_row['date'];
if ($sold >= $max && $date != date("Y-m-d") ) {
$sort = 'hot';
}else if($date == date("Y-m-d") && $sold <= $max){
$sort = 'new';
}else{
$sort = '';
}
echo '
<div class="product grid-item '.$sort.'">
<div class="product_inner">
<div class="product_image">
<img src="'.$img.'" alt="">
<div class="product_tag">'.$sort.'</div>
</div>
<div class="product_content text-center">
<div class="product_title text-long">'.$name.'</div>
<div class="product_price">₱'.number_format($price).'</div>
<div class="product_button ml-auto mr-auto trans_200">
<button class="product_button ml-auto mr-auto trans_200" id="add2c" data-prod=" '.$id.' " type="button" >add to cart</button>
</div>
</div>
</div>
</div>
';
} //End Foreach Loop
}
else{
echo "no products found";
}
?>
</div>
</div>
</div>
<!-- PAGINATION HERE -->
<?php echo $per_page_html; ?>
Method 1 => Without ajax
You can use the GET method for search value also. and in every pagination link
append the search value too.
for example.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
instead of above line use below one.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'&search='.$keyword.'">Next</a>';
Method 2 => using ajax
instead of href use a javascript function like below
$next_link = '<a class="paginate_next" href="#" onclick="paginate_fn(\''.$next_id.'\', \''.$keyword.'\'">Next</a>'
<script>
function paginate_fn(pageID, keyword){
$.ajax({
async: true,
type: 'get', // you can use post also
dataType:'json',
data: {'pageID':pageID, 'keyword': keyword},
url: "paget_name.php", // your page name
success: function (data) {
$('#search-content').html( data['content'] );
},
error: function () {
alert('An Error Occurred!.');
}
});
}
</script>

Content are not getting displayed. Facing issues in troubleshooting the my project on social media website for college

Edit: Issue has been resolved. The culprit was a misplaced single quote :P
The first image where content is getting displayed:
The second image is where no content is getting displayed
I have asked this question already a few days ago and my problem got solved there, but suddenly the problem occurred again and I can't seem to find the solution for it. What i'm trying to do is load the posts that will exceed 10 posts while scrolling but no posts are getting displayed when I'm adding Ajax.
Here is the code:
index.php code:
<?php
include("includes/header.php");
include("includes/classes/User.php");
include("includes/classes/Post.php");
if(isset($_POST['post']))
{
$post=new Post($con,$userLoggedIn);
$post->submitPost($_POST['post_text'],'none');
}
?>
<div class="user_details column">
<div class="user_details_left_right">
<a href="<?php echo $userLoggedIn; ?>">
<?php
echo $user['first_name'] . " " . $user['last_name'];
?>
</a>
<br>
<?php
echo "My Posts: " . $user['num_post'] . "<br>";
echo "Likes: " . $user['num_likes'];
?>
</div>
</div>
<div class="main_column column">
<form class="post_form" action="index.php" method="POST">
<textarea name="post_text" id="post_text" placeholder="Write something here..."></textarea>
<input type="submit" name="post" id="post_button" value="Post">
<hr>
</form>
<!--<?php
$post=new Post($con,$userLoggedIn);
$post->loadPostsFriends();
?>-->
<div class="posts_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function()
{
$('#loading').show();
//ajax request for loading 1st posts
$.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(data)
{
$("#loading").hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function()
{
var height=$('.posts_area').height(); //div containing posts
var scroll_top=$(this).scrollTop();
var page=$('.posts_area').find('.nextPage').val();
var noMorePosts=$('posts_area').find('.noMorePosts').val();
if((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false')
{
$('#loading').show();
alert("hello");
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(response)
{
$('.posts_area').find('.nextPage').remove(); //removes current next page
$('.posts_area').find('.noMorePosts').remove();
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //If end
return false;
}); //ending of $(window).scroll(function()
});
</script>
</div>
</body>
</html>
Post.php code:
<?php
class Post
{
private $user_obj;
private $con;
public function __construct($con,$user)
{
$this->con = $con;
$this->user_obj = new User($con,$user);
}
//$user_obj=new User($con,$userLoggedIn)
public function submitPost($body,$user_to)
{
$body=strip_tags($body); //To remove any HTML tag
$body=mysqli_escape_string($this->con, $body);
$check_empty=preg_replace('/\s+/','',$body); //To delete spaces
if($check_empty != "")
{
//Date and time
$date_added=date("Y-m-d H:i:s");
//get user name
$added_by=$this->user_obj->getUsername();
//If user is watching his/her own profile, user_to is none
if($user_to == $added_by)
{
$user_to = "none";
}
//Insert post
$query = mysqli_query($this->con,"INSERT INTO posts VALUES('','$body','$added_by','$user_to','$date_added','no','no','0')");
$returned_id=mysqli_insert_id($this->con);
//Insert noti
//Update posts count
$num_posts=$this->user_obj->getNumPosts();
$num_posts++;
$update_query=mysqli_query($this->con,"UPDATE users SET num_post='$num_posts' WHERE username='$added_by'");
}
}
public function loadPostsFriends($data,$limit)
{
$page=$data['page'];
$userLoggedIn=$this->user_obj->getUsername();
if($page == 1)
$start = 0;
else
$start = ($page-1) * $limit;
$str=""; //Str to return
$data_query=mysqli_query($this->con,"SELECT * FROM posts WHERE deleted='no' ORDER BY id DESC");
if(mysqli_num_rows($data_query) > 0)
{
$num_iterations = 0; //number of result checking
$count=1;
while($row=mysqli_fetch_array($data_query))
{
$id=$row['id'];
$body=$row['body'];
$data[] = $id;
$data[] = $body;
$added_by=$row['added_by'];
$date_time=$row['date_added'];
//prepare user_to string to include it even if not posted to an user
if($row['user_to'] == "none")
{
$user_to="";
}
else
{
$user_to_obj=new User($con,$row['user_to']);
$user_to_name=$user_to_obj->getFirstAndLastName();
$user_to="wrote to <a href'" . $row['user_to'] . "'>" . $user_to_name . "</a>";
}
//check if userwho posted has their account closed
$added_by_obj=new User($this->con,$added_by);
if($added_by_obj->isClosed())
{
continue;
}
if($num_iterations++ < $start)
continue;
//once 10 posts loaded just break
if($count > $limit)
{
break;
}
else
{
$count++;
}
$user_details_query=mysqli_query($this->con,"SELECT first_name,last_name,profile_pic FROM users WHERE username='$added_by'");
$user_row=mysqli_fetch_array($user_details_query);
$first_name=$user_row['first_name'];
$last_name=$user_row['last_name'];
$profile_pic=$user_row['profile_pic'];
//Datetime
$date_time_now=date("Y-m-d H:i:s");
$start_date=new DateTime($date_time); //Post date & time
$end_date=new DateTime($date_time_now); //Current time
$interval=$start_date->diff($end_date); //Difference between above 2 dates
if($interval->y >= 1)
{
if($interval==1)
$time_message=$interval->y . "year ago"; //1 year ago
else
$time_message=$interval->y . "year ago"; //More than 1 year ago
}
else if($interval-> m >= 1)
{
if($interval->d == 0)
{
$days=" ago";
}
else if($interval-> d == 1)
{
$days=$interval->d . " day ago";
}
else
{
$days=$interval->d . " days ago";
}
if($interval->m == 1)
{
$time_message=$interval->m . " month" . $days;
}
else
{
$time_message=$interval->m . " months" . $days;
}
}
else if($interval->d >= 1)
{
if($interval-> d == 1)
{
$time_message="Yesterday";
}
else
{
$time_message=$interval->d . " days ago";
}
}
else if($interval->h >=1)
{
if($interval-> h == 1)
{
$time_message=$interval->h . " hour ago";
}
else
{
$time_message=$interval->h . " hours ago";
}
}
else if($interval->i >=1)
{
if($interval-> i == 1)
{
$time_message=$interval->i . " minute ago";
}
else
{
$time_message=$interval->i . " minutes ago";
}
}
else
{
if($interval-> s < 30)
{
$time_message="Just Now!";
}
else
{
$time_message=$interval->s . " seconds ago";
}
}
$str .= "<div class='status_post'>
<div class='post_profile_pic'>
<img src='$profile_pic' width='50'>
</div>
<div class='posted_by' style='color:#BDBDBD;'>
<a href='$added_by'> $first_name $last_name </a> $user_to $time_message
</div>
<div id='post_body'>$body<br></div>
</div><hr>";
}
if($count > $limit)
$str .= "<input type='hidden' class='nextPage' value='" . ($page+1) . "'><input type='hidden' class='noMorePosts' value='false'>";
else
$str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align:center;'>No more posts!</p>";
}
echo $str;
}
}
?>
user.php code:
<?php
class User
{
private $user;
private $con;
public function __construct($con,$user)
{
$this->con = $con;
$user_details_query=mysqli_query($con,"SELECT * FROM users WHERE username='$user'");
$this->user = mysqli_fetch_array($user_details_query);
}
//$user_obj=new User($con,$userLoggedIn)
public function getUsername()
{
return $this->user['username'];
}
public function getNumPosts()
{
$username=$this->user['username'];
$query=mysqli_query($this->con,"SELECT num_post FROM users WHERE username='$username'");
$row=mysqli_fetch_array($query);
return $row['num_post'];
}
public function getFirstAndLastName()
{
$username=$this->user['username'];
$query=mysqli_query($this->con, "SELECT first_name, last_name FROM users WHERE username='$username'");
$row=mysqli_fetch_array($query);
return $row['first_name'] . " " . $row['last_name'];
}
public function isClosed()
{
$username=$this->user['username'];
$query=mysqli_query($this->con,"SELECT user_closed FROM users WHERE username='$username'");
$row=mysqli_fetch_array($query);
if($row['user_closed']=='yes')
return true;
else
return false;
}
public function isFriend($username_to_check)
{
$usernameComma="," . $username_to_check . ",";
if((strstr($this->user['friend_array'],$usernameComma)) || $username_to_check==$this->user['username'])
{
return true;
}
else
{
return false;
}
}
}
?>
ajaxloadpost.php code:
<?php
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit=10; //Limit post to 10 each time
$posts=new Post($con,$_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST,$limit);
?>

Class pagination

I have problem error for load page 2,3,4 n etc of my original link is http://bali-webdesign.com/staging/astina3/subkategori-Bali%20Package-3-3.htm..
here my class_paging.php
class Paging{
function cariPosisi($batas){
if(empty($_GET['halaman'])){
$posisi=0;
$_GET['halaman']=1;
}
else{
$posisi = ($_GET['halaman']-1) * $batas;
}
return $posisi;
}
function jumlahHalaman($jmldata, $batas){
$jmlhalaman = ceil($jmldata/$batas);
return $jmlhalaman;
}
function navHalaman($halaman_aktif, $jmlhalaman){
$link_halaman = "";
// Link ke halaman pertama (first) dan sebelumnya (prev)
if($halaman_aktif > 1){
$prev = $halaman_aktif-1;
$link_halaman .= "<li class='paginate_button previous' id='table-gallery_previous'><a aria-controls='table-gallery' data-dt-idx='0' tabindex='0' href=$_SERVER[PHP_SELF]?halaman=1>«</a></li>
<li><a href=$_SERVER[PHP_SELF]?halaman=$prev>‹</a></li>";
}
else{
$link_halaman .= "<li class='disabled'><a>«</a></li><li class='disabled'><a>‹</a></li>";
}
// Link halaman 1,2,3, ...
$angka = ($halaman_aktif > 3 ? "" : " ");
for ($i=$halaman_aktif-2; $i<$halaman_aktif; $i++){
if ($i < 1)
continue;
$angka .= "<li><a href=$_SERVER[PHP_SELF]?halaman=$i>$i</a></li>";
}
$angka .= "<li class='paginate_button active'><a aria-controls='table-gallery' data-dt-idx='1' tabindex='0'>$halaman_aktif</a></li>";
for($i=$halaman_aktif+1; $i<($halaman_aktif+3); $i++){
if($i > $jmlhalaman)
break;
$angka .= "<li><a aria-controls='table-gallery' data-dt-idx='1' tabindex='0' href=$_SERVER[PHP_SELF]?halaman=$i>$i</a></li>";
}
$angka .= ($halaman_aktif+2<$jmlhalaman ? "<li><a href=$_SERVER[PHP_SELF]?halaman=$jmlhalaman>$jmlhalaman</a></li>" : " ");
$link_halaman .= "$angka";
// Link ke halaman berikutnya (Next) dan terakhir (Last)
if($halaman_aktif < $jmlhalaman){
$next = $halaman_aktif+1;
$link_halaman .= "<li class='paginate_button next' id='table-gallery_next'><a aria-controls='table-gallery' data-dt-idx='2' tabindex='0' href=$_SERVER[PHP_SELF]?halaman=$next>›</a></li><li><a href=$_SERVER[PHP_SELF]?halaman=$jmlhalaman>»</a></li>";
}
else{
$link_halaman .= "<li class='disabled'><a href='#'>›</a></li><li class='disabled'><a href='#'>»</a></li>";
}
return $link_halaman;
}
}
then in my page which I load pagination function
include "inc/config/class_paging.php";
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$s = new Paging;
$batas = 10;
$posisi = $s->cariPosisi($batas);
$produk = mysql_query("SELECT * FROM produk where id_subkategori='$_GET[idkk]' LIMIT $posisi,$batas");
$jmldata = mysql_num_rows(mysql_query("SELECT * FROM produk"));
while($p=mysql_fetch_array($produk)){
echo "blabla";
}
$jmlhalaman = $s->jumlahHalaman($jmldata, $batas);
$linkHalaman = $s->navHalaman($_GET[halaman], $jmlhalaman);
echo "<div align='center' class='dataTables_paginate paging_simple_numbers' id='table-about_paginate'>
<ul class='pagination'>$linkHalaman</ul>
</div>";
Right now, when I click page 2 button of pagination, the result link will be bali-webdesign.com/staging/astina3/subkategori.php?halaman=2 but that link can't show my data. I want when I click page 2 button of pagination will show my data
what should I change in class_paging.php for link url so it can show data on page 2,3,4 n etc

creating a moustache.js html template using JSON

I just learned about moustache.js and i am attempting to create an HTML template. However, the documentation is a bit hard to decipher. I found a good site that explains partials (which I believe I will need). I was hoping someone might be able to just 'get me started' on how I would need to do this.
I have a php file that I need to convert to the template:
PHP:
<div id='board'>
<?php
if ($threads)
{
$count = count($threads);
$perpage = 17;
$startlist = 3;
$numpages = ceil($count / $perpage);
if ($page == 'home') {$page = 1;}
$threadstart = ($page * $perpage) - $perpage;
$i = 0;
echo "<table class='board'>
<tr>
<th width='5%'><img src='".base_url()."img/board/icons/category_icon.png' alt='category_icon'/></th>
<th width='5%'>Tag</th>
<th width='50%'>Subject</th>
<th width='7.5%'>Author</th>
<th width='7.5%'>Replies/Views</th>
<th width='15%'>Last Post</th>
</tr>";
foreach ($threads as $list)
{ $i++;
$thread_owner = $this->thread_model->get_owner($list['owner_id']);
$thread_id = $list['thread_id'];
$query = $this->db->query("SELECT f.tag FROM filter_thread AS ft
INNER JOIN filter AS f ON ft.filter_id = f.filter_id
WHERE thread_id = $thread_id");
$result = $query->result_array();
$trunc_body = $this->thread_model->get_reply_summary($thread_id);
$filter = "";
$filter2 ="";
$ent = "entertainment";
foreach ($result as $string)
{
if ($string['tag'] == $ent) {
$filter2 .= "<div id='entertainment'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/entertainment_icon.png' title='Entertainment' alt='Entertainment'/>";
$filter2 .= "</p></div>";
} else {
$filter2 .= "<div id='misc'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/misc_icon.png' title='Misc' alt='Misc'/>";
$filter2 .= "</p></div>";
$filter .= " [".$string['tag']."]";
}
}
if (!$result) { $filter = "" AND $filter2 =""; }
if ($i > $threadstart AND $i <= $threadstart + $perpage)
{
echo "<tr>";
echo "<td>".$filter2."</td>";
echo "<td>".$filter."</td>";
echo "<td title='".$trunc_body['0']['body']."'>".ucfirst($list['subject'])."<div id='filter'><p></p></div></td>";
echo "<td><p>".$thread_owner."</p></td>";
echo "<td align='right'>Replies: ".$list['replies_num']."<br>Views: ".$list['views']."</td>";
$owner = $this->thread_model->get_owner($list['last_post_id']);
echo "<td>".$owner." <br>".$list['replystamp'] ."</td></tr>";
}
}
echo "</table>";
echo "<br>";
echo "Current Page: $page | ";
echo "Page: ";
for ($n = 1; $n < $numpages+1; $n++)
{
echo "<a href=".base_url()."main/home/$n>$n</a> | ";
}
}
?>
</div>
And here is the AJAX
$(function() {
$('#all').addClass('ui-selected')
$( "#selectable" ).selectable({
selected: updatefilters
});
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
url: 'updatefilters',
dataType: 'json',
data: { filters: filters },
success: function(data){
var template = "<div id ='board'>TESTING{{#body}}<table>";
var partials = "{{#subject}}";
//for (i=0 ; i< data.length ; i++)
//{html += "<tr><td>" + data[i].subject + "</td><td>" + data[i].body + "</td></tr>";}
//html += "</table></div>";
var html = Moustache.to.html(template, data, partials);
$('#board').html(html);
}
});
}
});
Im not sure how to navigate through the JSON array with moustache..and as it is, it does not update the page, though the commented out parts DO.
Thanks in advance!
First of all if you are receiving a json string you will need to to parse it (use $.parseJSON(data))
Once you have the data parsed you need to loop throught the JSON attributes.
For example:
If JSON has the following: body: {content: [dataObj:{data:'a'}, dataObj[data:'b']]}
do
<div>{{#body}}<div>
<div>{{#content}}<div>
<div>{{#dataObj}}<div>
<span>{{data}}<span>
If you are using partial, you will need to call them inside the main template.
Check the moustache5 documentation, it has improved a lot.

Pagination not taking value to second page?

$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '')
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
echo "";
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
Pagination is working correctly for select $today. Here pagination is not taking value to second page in the case of select $mydate. If second page of $mydate clicks, again going to $today. ie Second click is not posting $mydate to next page. How can I take the value to second page?
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
function pagination in your code is not returning the resulting mysql query resource, and your code is not receiving that from the pagination function call
you need
to add return $pg_result; in your pagination function
and add $result=pagination(....
Edit:
Sorry, I noticed you added pg_result to global, which does not need return and the solution I said, but you don't need mysql_query and fetch before that and I don't see where you print the results. there is only echo "", you can try the one I edited last, and see if it works for you.
Edit:
$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
//$result=mysql_query($sql);
$pg_result=pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '' && is_resource($pg_result))
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
var_dump($data);
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
return $pg_result;
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
Looks like you're mixing up the concept of $_POST and $_GET.
By having your pagination links point to '<a href="'.$pg_page_name.'?page_id='.$i . $pg_user_param.'"... You should be intercepting $_GET['page_id'] before you make your SQL query.
Your top code references $_POST['datepicker'] but you don't mention a form anywhere and your pagination links certainly aren't posting that data in your example.
You should use $pg_param = ""; to pass your own query parameters. Ex: &date=$date_value:
$pg_param = "&date=$date_value";

Categories