Fetch new MySQL entries and append to existing div's dynamically - php

I have a PHP script to selected records for comments from a database, and then print them onto the page. What I'd like to happen is that if a user is on a page, and another user comments on an item on said page, it automatically appends the new comment to the bottom. The problem I'm having is that I don't know how to differentiate between all of the statuses.
My code for generating the comments on a status is:
<?php
$rt = ("SELECT * FROM (SELECT comment as comment, byuid as byuid, comuid as comuid, likes as likes, dislikes as dislikes, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_comments WHERE onuid = '$sid' AND type = 'status' ORDER BY timestamp DESC LIMIT 2) mingle_comments ORDER BY timestamp ASC"); //query
$result = mysql_query($rt) or die (mysql_error());
if(mysql_num_rows($result) >= 2) {
?>
<div id="sa" style="background:#E0E0E0; padding:5px 5px 5px 5px;">
View all comments...
</div>
<?php
}
while($st = mysql_fetch_assoc($result)) {
$comment = nl2br($st['comment']);
$by = $st['byuid'];
$comuid = $st['comuid'];
$time = $st['timestamp'];
$l = $st['likes'];
$d = $st['dislikes'];
$bq = "SELECT * FROM users WHERE uid = '$by' LIMIT 1";
$bqq = mysql_query($bq) or die (mysql_error());
while($bqr = mysql_fetch_assoc($bqq)) {
$dp = $bqr['dp'];
$fbq = $bqr['fname'];
$sbq = $bqr['sname'];
}
?>
<div id="commentbox" class="<?php echo $comuid; ?>" style="padding:5px 5px 5px 5px;">
<div id="cbi" style=" display:inline; position:relative; ">
<img src="<?php if ($dp == null) { echo 'img/unknown_user.jpg'; } else { echo "pf/" . $by . "/" . $dp; } ?>" width="36px" style=" display:inline; position:relative;"/>
</div>
<div id="cbt" style="position:relative; margin-left:32px; margin-top:-35px;">
<?php echo $fbq . " " . $sbq; ?>
<p class="<?php echo $comuid; ?>" style="position:relative; margin-left:5px;"><?php echo $comment; ?></p>
</div>
<div id="clb" style="background:#E0E0E0; padding-left:5px;">
Like<?php echo time_since($time); ?>
</div>
</div>
<?php
}
?>
TL:DR; How can I automatically fetch new comments and append them to the comments generated in the above script without page refresh.

JQUERY
$(document).ready(function(){
var lastcheck='';
setInterval(function() {
$.ajax({
url: 'URL_TO_PHP_SCRIPT',
type: 'POST',
data: {'lastcheck':lastcheck},
success: function(result){
if (result!='nothing_new'){
lastcheck=result.lastcheck /*Update lastcheck*/
var data=result.data;
$.each(data, function(i,val){
//Foreach comment you do what you need, like append, prepend, etc. data[i]."key" to get the value.
});
}
}
});
}, 15000 /* This will check each 15 seconds, you can change it */);
});
PHP SIDE
$lastcheck=$_POST['lastcheck'];
/*
You should add a date field to each new created comment,then filter by "orderby date > $lastcheck" so you get comments since your last check
You get the new comments here
...
...
..
*/
if (!empty($arrayofnewcomments)){
/*The output*/
echo json_encode(array('lastcheck'=>date('Y-m-d H:i:s'),'data'=>$arrayofnewcomments));
}else{/*No new comments*/
echo 'nothing_new';
}
This is some code I came up with, it's a general Idea but it works. It will check each 15 seconds for new comments.

Related

Show / hide php mysql results with loader

I have MySQL database results.
I want to show 3 rows and then hide rest.
When the user clicks to load more data then to appear all rows.
The problem is when I click show more, then only one more row appears.
<?php
$query_brands = mysql_query("SELECT distinct pd_filter1 from tbl_brands2 WHERE pd_code in (select pd_code from tbl_product where cat_id='2')") or die(mysql_error());
$count_brands = mysql_num_rows($query_brands);
if($count_brands > 0) {
while($fetch_brands = mysql_fetch_array($query_brands)) {
$record_brands[] = $fetch_brands;
}
}
$i_brands=0;
foreach($record_brands as $records_brands) {
?>
<table border="1" width="215" style="border-collapse: collapse; border-spacing: 0;" bgcolor="#eeeff0">
<tr>
<td>
<?php
$i_brands = $i_brands + 1;
if ($i_brands > 3)
{
?>
<div id="myDIV_Filter1_1" style="display:none";>
<?php
}
}
?>
<div id="myDIV_Filter1_2">
<span class="class22">
show more...
</span>
</div>
<div id="myDIV_Filter1_3" style="display:none";>
<span class="class22">
show less...
</span>
</div>
</td>
</tr>
</table>
JavaScript
function myFunction() {
var x_filter1_1 = document.getElementById("myDIV_Filter1_1");
var x_filter1_2 = document.getElementById("myDIV_Filter1_2");
var x_filter1_3 = document.getElementById("myDIV_Filter1_3");
if (x_filter1_1.style.display === "none") {
x_filter1_1.style.display = "block";
x_filter1_2.style.display = "none";
x_filter1_3.style.display = "block";
} else {
x_filter1_1.style.display = "none";
x_filter1_2.style.display = "block";
x_filter1_3.style.display = "none";
}
}
You have some errors on your code:
1) Try not to use return the way you are using right now in code lines like this one:
show more...
You can use it better like it's explained here
2) You have all your divs of the code example in display none, the user will never see the information in those divs because you don't have any code to start showing some of them. In the same line you put a ";" after the style but it must be inside the style. This line has an error:
<div id="myDIV_Filter1_3" style="display:none";>
It must be this way:
<div id="myDIV_Filter1_3" style="display:none;">
The "show-hide" logic on your javascript function myFunction has an error because your div id="myDIV_Filter1_1" contains the other 2 div you have on your code example so you can't hide this particular div because you will lose the "show" or "hide" of the other 2 divs. That way it'll never show you the other 3 rows you wanted to see. I fixed all the errors you can check the code on my snippet here:
function myFunction() {
var x_filter1_1 = document.getElementById("myDIV_Filter1_1");
var x_filter1_2 = document.getElementById("myDIV_Filter1_2");
var x_filter1_3 = document.getElementById("myDIV_Filter1_3");
if (x_filter1_3.style.display === "none") {
x_filter1_1.style.display = "block";
x_filter1_2.style.display = "none";
x_filter1_3.style.display = "block";
} else {
x_filter1_1.style.display = "block";
x_filter1_2.style.display = "block";
x_filter1_3.style.display = "none";
}
}
<?php
$query_brands = mysql_query("SELECT distinct pd_filter1 from tbl_brands2 WHERE pd_code in (select pd_code from tbl_product where cat_id='2')") or die(mysql_error());
$count_brands = mysql_num_rows($query_brands);
if($count_brands > 0) {
while($fetch_brands = mysql_fetch_array($query_brands)) {
$record_brands[] = $fetch_brands;
}
}
$i_brands=0;
foreach($record_brands as $records_brands) {
?>
<table border="1" width="215" style="border-collapse: collapse; border-spacing: 0;" bgcolor="#eeeff0">
<tr>
<td>
<?php
$i_brands = $i_brands + 1;
if ($i_brands > 3)
{
?>
<div id="myDIV_Filter1_1">
<?php
}
}
?>
<div id="myDIV_Filter1_2" >
<span class="class22">
show more...
</span>
</div>
<div id="myDIV_Filter1_3" style="display:none">
<span class="class22">
show less...
</span>
</div>
</td>
</tr>
</table>
Hope it helps!

jQuery prevents foreach loop from working?

I'm trying to create a collapsible div for each order in a customers account. The code works fine without the jquery.
But when I use jquery, and try to expand the div, there's nothing in there, it's just blank.
Here's the the PHP:
<div class="container">
<h1> My Orders </h1>
<?php
$user_id = $_SESSION['user_session'];
$stmtGetOrderNumber = $DB_con->prepare("SELECT DISTINCT order_id FROM orders WHERE user_id = :user_id");
$stmtGetOrderNumber->bindparam(":user_id",$user_id);
$stmtGetOrderNumber->execute();
$orderids=$stmtGetOrderNumber->fetchAll(PDO::FETCH_ASSOC);
$stmtGetOrderItems = $DB_con->prepare("SELECT * FROM orders as o
INNER JOIN products as p ON p.product_id=o.product_id
INNER JOIN users as u ON u.user_id=o.user_id
WHERE order_id = :this_order_id
ORDER BY order_date_added DESC");
$stmtGetOrderItems->bindparam(":this_order_id", $id['order_id']);
$stmtGetOrderItems->execute();
$orders=$stmtGetOrderItems->fetchAll(PDO::FETCH_ASSOC);
foreach($orderids as $id)
{
$nameshown = false;
$emailshown = false;
$dateshown = false;
echo '<div class="list-group" style="padding-bottom:1%;">';
echo '<h1 class="list-group-item active">Order ID: ',$id['order_id'],'</h1>';
echo '<div class="header"> <span>Expand</span> </div>';
echo '<div class="content">';
foreach($orders as $order)
{
echo'<p>',$order['product_name'],'</p>';
echo'<p>£',$order['product_price'],'</p>';
echo'<img id="img" class="img-fluid" src="images/',$order['product_image'],'" style="height:100px;width:100px;">';
echo'<hr>';
}
echo'</div></div>';
}
?>
</div>
And the jQuery:
$(".header").click(function () {
$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
//execute this after slideToggle is done
//change text of header based on visibility of content div
$header.text(function () {
//change text based on condition
return $content.is(":visible") ? "Collapse" : "Expand";
});
});
});
And the styles for the div's (Not sure if this is necessary):
.container {width:100%;}
.container div {width:100%;}
.container .header {background-color:#d3d3d3;padding: 2px;cursor: pointer;font-weight: bold;}
.container .content{display: none;padding : 5px;}

Refresh div contents without closing dropdown

I'm trying to learn php, mysql and javascript/jquery by building a live bidding system. I want to refresh the value of a bid button and dropdown automatically, but only if the value has changed. I've made a bidbuttons.php that outputs the buttons after querying the db for the current values, and I load and reload the page with this jquery I found elsewhere. I have tried several different methods of refreshing the div, and the best I came up with unfortunately closed the dropdown on the timer. This current version was described as exactly what I need but doesn't seem to work, in fact it logs me out. would prefer the div to refresh and the dropdown to close ONLY if the bidbuttons.php is updated. This is my first post, I hope I did this right.
<div id="bidbuttons"></div>
<script type="text/javascript">
var loadUrl = "includes/bidbuttons.php?id='.$item->id.'";
$("#bidbuttons").load(loadUrl).fadeIn("slow");
var auto_refresh = setInterval(function () {
$.get(loadUrl, function(data) {
if (data.changed) {
$("#bidbuttons").load(loadUrl).fadeIn("slow");
}
});
}, 10000);
</script>
and my bidbuttons.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$getid = (int)$_GET['id'];
// get current price
$result = $mysqli->query("SELECT ammount, bidder_id FROM bids WHERE ammount=(SELECT MAX(ammount)) && item_id like $getid order by ammount desc");
while($row = $result->fetch_assoc()) {
$bidder_id = $row["bidder_id"];
$current = $row['ammount'];
echo ($mysqli->error);
$result->free();
}
//get item info
$results = $mysqli->query("SELECT * FROM items WHERE id like $getid ");
while($row = $results->fetch_assoc()) {
if (empty ($current)) { $current = $row["start"];}
$title = $row["title"];
$item->thenext = ($current + $row["raise"]);
$buyout = $row["buyout"];
$raise = $row["raise"];
$sold = $row["sold"];
}
$results->free();
echo ('<div id="buttons">
<a class="btn btn-primary btn-lg" style="margin-bottom: 10px; margin-top: 10px; width: 80%;" href="includes\placebid.php?itemid=' . $getid . '&ammount=' . $item->thenext .'">Bid $' . $item->thenext . '</a>
');
if ($buyout){echo ('
<a class="btn btn-success btn-lg" style="margin-bottom: 10px; width: 80%;" href="includes\placebid.php?itemid='.$getid.'&ammount='.$buyout.'">Buyout $'.$buyout.'</a>
');}
echo '</div><!-- buttons -->';
echo ('
<div class="dropdown">
<button style="margin-bottom: 10px; width: 80%;" type="button" class="btn btn-info btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Custom Bid<span class="caret"></span></button>
<ul class="dropdown-menu">
');
// build the custom bid dropdown
if (!$buyout) { $maxcust = $item->thenext*25;
for ($cust = $item->thenext; $cust <= $maxcust; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
if ($buyout) {
for ($cust = $item->thenext; $cust <= $buyout; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
echo ('
</ul>
</div><!-- dropdown -->
');
}
mysqli_close($mysqli);
?>
I think the problem may be in that your PHP file is generating HTML which is continually replacing elements on your page due to them being loaded via AJAX.
Just an idea but you could make your PHP output a JSON instead that contains the database results, then have jQuery read the output. Your code would then process that JSON file and create or update the HTML elements accordingly (rather than replace them).
This way you have more fine grained control in the JavaScript for when your dropdown should close.
See this answer if you'd like to output from MySQLi to JSON.

php extract from array/query and define php session variable by row without overwriting

I have a mySQL database that is queried and displayed in tables in index.php. I have a file called up.php that handles a click on an < a > in each table that is output from the query in index.php. I need to have a variable that I can extract from a field in each seperate row that is queried, so that when the < a > is clicked it passes the variable to the up.php file to be manipulated. Right now the variable is just being over written and is equal to the value of the last row queried and the database is updated frequently, so I can't just set one to each row, it has to be dynamic.
Here is the index.php file
<?php
$sql = mysql_query("SELECT * FROM blogData ORDER BY id DESC");
//query for even numbered rows where mes_id = even
$sql2=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 0 ORDER BY mes_id DESC");
//query for odd numbered rows where mes_id = even
$sql3=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 1 ORDER BY mes_id DESC");
while(($row = mysql_fetch_array($sql))AND($row2 = mysql_fetch_array($sql2))AND($row3 = mysql_fetch_array($sql3)) ){
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$category = $row['category'];
$podcast = $row['podcast'];
$datetime = $row['datetime'];
$message1=$row2['msg'];
//******* this is the variable from the query that needs to be held and not overwritten ********
$mes_id1=$row2['mes_id'];
$totalvotes1=$row2['totalvotes'];
$message2=$row3['msg'];
//******* this is the second variable from the query that needs to also be held and not overwritten *******
$mes_id2=$row3['mes_id'];
$totalvotes2=$row3['totalvotes'];
//attempting to implement this array...? not sure how to use it correctly...
$valuess[]=$row2['mes_id'];
//******* I was trying to use these session variables in up.php but they were being overwritten in the query ********
$_SESSION['message1'] = $row2['msg'];
$_SESSION['message2'] = $row3['msg'];
$_SESSION['mes_id1'] = $row2['mes_id'];
$_SESSION['mes_id2'] = $row3['mes_id'];
$_SESSION['totalvotes1'] = $row2['totalvotes'];
$_SESSION['totalvotes2'] = $row3['totalvotes'];
$_SESSION['valuess'] = $valuess[1];
?>
<?php
// variable used to display file name of $podcast without the extension
$noext = $podcast;
$echodub = rawurlencode($podcast);
// code to display $noext without the file extension
$info = pathinfo($noext);
$noext_name = basename($noext,'.'.$info['extension']);
?>
<!-- ********* echo php variables in html format, in a table with the class of "podcast" -->
<table class="podcast" border="1">
<tr>
<td class="title">
<?php echo $title; ?>
</td>
<td class="timeandcategory">
<?php echo $datetime; ?> <br>
<?php echo $category; ?>
<?php echo $_SESSION['mes_id1']; ?>
<?php echo $_SESSION['mes_id2']; ?>
<?php echo session_id(); ?>
</td>
</tr>
<tr>
<td class="content">
<?php echo $content; ?>
</td>
<td class="myfblike">
<span class='st_fblike_large' displayText='Facebook Like'></span><br>
<span class='st_facebook_large' displayText='Facebook'></span><br>
<span class='st_twitterfollow_large' displayText='Twitter Follow'></span><br>
<span class='st_pinterest_large' displayText='Pinterest'></span><br>
<span class='st_email_large' displayText='Email'></span><br>
<span class='st_sharethis_large' displayText='ShareThis'></span><br>
</td>
</tr>
<tr>
<td class="audio">
<!--echo the audio file -->
<ul class="playlist">
<li><?php echo"$noext_name"; ?></li>
</ul>
</td>
<td>
<!-- ********** this is the cell in the table where the veriables need to be held and sent to up.php ******** -->
<div id="main">
<div id="left">
<span class='up'><img src="up.png" alt="Down" /></span><br />
<?php echo $_SESSION['totalvotes1'] ?><br />
</div>
<div id="message">
<?php echo $_SESSION['message1'] ?>
</div>
<div class="clearfix"></div>
</div>
//********the down.php file is the same as the up.php file... just with opposite variables... im not concerned with this yet until i get the variables to display correctly in up.php
<div id="main">
<div id="left">
<br />
<?php echo $_SESSION['totalvotes2'] ?><br />
<span class='down'><img src="down.png" alt="Down" /></span>
</div>
<div id="message">
<?php echo $_SESSION['message2'] ?>
</div>
<div class="clearfix"></div>
</div>
</td>
</tr>
</table>
<br>
<?php
}
?>
and here is the up.php file
up.php
<?php
session_start();
include("config.php");
$message1 = $_SESSION['message1'];
$message2 = $_SESSION['message2'];
$mes_id1 = $_SESSION['mes_id1'];
$mes_id2 = $_SESSION['mes_id2'];
$totalvotes1 = $_SESSION['totalvotes1'];
$totalvotes2 = $_SESSION['totalvotes2'];
$ip=$_SERVER['REMOTE_ADDR'];
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$mes_id1' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
$ip_sql2=mysql_query("select ip_add from Voting_IP where mes_id_fk='$mes_id2' and ip_add='$ip'");
$count2=mysql_num_rows($ip_sql2);
//********* testing if these variables are being passed.....
echo $mes_id1;
echo $mes_id2;
$valuess[0] = $_SESSION['valuess'];
echo $valuess[0];
//********
// if the user has already voted, execute script
if($count==0 && $count2!=0)
{
$sql = "update Messages set totalvotes=totalvotes+1 where mes_id='$mes_id1'";
mysql_query( $sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$mes_id1','$ip')";
mysql_query( $sql_in);
$sql = "update Messages set totalvotes=totalvotes-1 where mes_id='$mes_id2'";
mysql_query( $sql);
$sql_in = "DELETE FROM Voting_IP WHERE mes_id_fk='$mes_id2'";
mysql_query( $sql_in);
// if the user has not voted, execute script
}
else if($count==0 && count2==0)
{
$sql = "update Messages set totalvotes=totalvotes+1 where mes_id='$mes_id1'";
mysql_query( $sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$mes_id1','$ip')";
mysql_query( $sql_in);
echo $mes_id1;
echo $mes_id2;
}
?>
Thank you so much to anybody who is able to help me!
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
} });
}
else
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
});
});
With the javascript, I can see what you need to do in order to get it working how you want.
Instead of putting the key1=value1 etc attached to the href, put it in its own attribute called data-options, without the ? pre-pending it. So looking like:
Up/Down
From there, you would modify the JS to be:
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
From there, you would access them in the up.php and down.php files by using $_POST['key1'], and only need to echo out what your JS is expecting in return from its AJAX call. ^^

Limit Pagination (1 2 3 4 5 .. 30 31 32 33)

I have a system in php, ajax and jquery. This system will search the database queries per page 5 and divide the results into several pages. The problem is that the more the results are more pages are displayed. In the current code, paging is like this: first 1 2 3 4 5 6 last. I would like to remain so: first 1 2 ... 5 6 last. Ie I want to limit the pagination. If I do not limit the pagination when they have more results would look like this: 1234567891011 ...
The code:
<script type="text/javascript">
$(document).ready(function(){
function showLoader(){
$('.search-background').fadeIn(200);
}
function hideLoader(){
$('.search-background').fadeOut(200);
};
$(".pagcon li").click(function(){
showLoader();
$(".pagcon li").removeClass('current');
$(this).addClass("current");
$("#resultado").load("data.php?page=" + this.id, hideLoader)
return false;
});
$("#1").addClass("current");
showLoader();
$("#resultado").load("data.php?page=1", hideLoader);
});
</script>
<style type="text/css">
#consultas {
width:780px;
min-height:245px;
overflow:hidden;
}
.search-background {
background:#FFF;
display:none;
height:154px;
position:absolute;
padding-top:84px;
text-align:center;
opacity:0.5;
filter:alpha(opacity=50);
width:780px;
z-index:999;
}
</style>
<div id="consultas">
<?php
$per_page = 5;
$sql = "select * from consultas ";
$rsd = mysql_query($sql);
$count = mysql_num_rows($rsd);
$pages = ceil($count/$per_page);
?>
<div class="search-background">
<label><img title="Carregando..." src="loader.gif" alt="" /></label>
</div>
<div id="resultado">
</div>
</div>
<ul class="pagination clearfix pagcon">
<?php
//Show page links
echo '<li id="1"><a title="Página 1" href="#">Primeiro</a></li>';
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo '<li id="'.$pages.'"><a title="Página '.$pages.'" href="#">Último</a></li>';
?>
</ul>
data.php:
<?php
include_once("config.php"); //MYSQL CONFIG
$per_page = 5;
$sqlc = "show columns from consultas";
$rsdc = mysql_query($sqlc);
$cols = mysql_num_rows($rsdc);
$page = $_REQUEST['page'];
$start = ($page-1)*5;
$sql = "select * from consultas ORDER BY data DESC LIMIT $start,5";
$rsd = mysql_query($sql);
?>
<?php
while ($rows = mysql_fetch_assoc($rsd))
{?>
<div class="message status success">
<span><b><?php echo $rows['consulta']; ?> (<font color="#8D4B19"><?php echo $rows['codigo']; ?></font>)</b></span>
<span><?php if(strlen($rows['user']) >= 30){ echo substr($rows['user'], 0, 30)."..."; } else { echo $rows['user']; } ?></span>
<span><b><?php echo $rows['operacao']; ?></b></span>
<span><?php echo date("d/m/Y", strtotime($rows['data'])); ?></span>
<span>R$ <?php echo $rows['valor']; ?></span>
</div>
<?php
}?>
<script type="text/javascript">
$(document).ready(function(){
var Timer = '';
var selecter = 0;
var Main =0;
bring(selecter);
});
function bring ( selecter )
{
$('div.status:eq(' + selecter + ')').stop().animate({ opacity: '1.0', height: '34px' },300,function(){
if(selecter < 6)
{
$('div.status').stop().animate({ opacity: '1.0', height: '17px' },300);
clearTimeout(Timer);
}
});
selecter++;
var Func = function(){ bring(selecter); };
Timer = setTimeout(Func, 20);
}
</script>
Try
$threshold=1;
for($i=1; $i<=$threshold+1; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo " ... ";
for($i=$pages-$threshold; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
By varying $threshold you can vary the number of page links available.
However, it would be better to present the results as first ... 3 4 5 ... last instead if the user is on the fourth page. This way they can easily move between adjacent pages. Also you can run through the loop fewer times. $current_page is the current page you are on. This needs to be made available to the pagination code somehow.
$threshold=1;
$lower_limit=(($current_page-$threshold)>1)?$current_page-$threshold:1;
$upper_limit=(($current_page+$threshold)<$pages)?$current_page-$threshold:$pages;
for($i=$lower_limit; $i<=$upper_limit; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
Edit for the sake of this specific question
Your pagination is once and not reloaded in the ajax. In order to achieve this reduced pagination, you either need to
load only a few link elements as in either of the choices above and add new link elements or
load all the link elements but hide unnecessary links until they are required.
For the latter:
php
$threshold=1;
for($i=1; $i<=$threshold+1; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo " ... ";
for($i; $i<=$pages; $i++)
{
echo '<li id="'.$i.'"'.($i<($pages-$threshold)?'style="display:none"':'')'>'.$i.'</li>';
}
javascript
$(".pagcon li").click(function(){
showLoader();
$(".pagcon li").hide();//hide all links
$(".pagcon li").removeClass('current');
$(this).addClass("current").show();
var id=parse_int($(this).attr(id));
$(".pagcon li:first, .pagcon li:first, .pagcon li#"+(id-1)+" .pagcon li#"+(id+1)).show();//show adjacent links and 'First' and 'Last'
$("#resultado").load("data.php?page=" + this.id, hideLoader)
return false;
});

Categories