I am trying to create pagination code without refreshing the page using jquery, php and mysql. I found away to do it but I can't retrieve my post data because they are sent from the previous page the main.php page and the pagination code is in another page called pagination.php. I believe the post data wont be lost if I Integrate the two pages into one but when I tried to make it it didn't work.
main page
include('db.php');
$per_page = 1;
$select_table = "select * from pagination";
$variable = mysql_query($select_table);
$count = mysql_num_rows($variable);
$pages = ceil($count/$per_page)
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Qjuery pagination with loading effect using PHP and MySql</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function Display_Load()
{
$("#load").fadeIn(1000,0);
$("#load").html("<img src='load.gif' />");
}
function Hide_Load()
{
$("#load").fadeOut('slow');
};
$("#paginate li:first").css({'color' : '#FF0084'}).css({'border' : 'none'});
Display_Load();
$("#content").load("pagination.php?page=1", Hide_Load());
$("#paginate li").click(function(){
Display_Load();
$("#paginate li")
.css({'border' : 'solid #193d81 1px'})
.css({'color' : '#0063DC'});
$(this)
.css({'color' : '#FF0084'})
.css({'border' : 'none'});
var pageNum = this.id;
$("#content").load("pagination.php?page=" + pageNum, Hide_Load());
});});
</script>
</head>
<body>
<div id="content" ></div>
<div class="link" align="center">
<ul id="paginate">
<?php
//Show page links
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
?>
</ul>
</div>
<div style="clear:both"> </div>
<div id="load" align="center" ></div>
</body>
</html>
pagination page
<?php
include('db.php');
$per_page = 1;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$select_table = "select * from pagination where date = ' =$date' and number ='$number' $start,$per_page";
$variable = mysql_query($select_table);
?>
<table width="800px">
<?php
$i=1;
while($row = mysql_fetch_array($variable))
{
$name=$row['name'];
$design=$row['designation'];
$place=$row['place'];
?>
<tr>
<td style="color:#999;"><?php echo $i++; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $design; ?></td>
<td><?php echo $place; ?></td></tr>
<?php
}
?>
</table>
I get an error from pagination.php page in this line:
$select_table = "select * from pagination where date = ' =$date' and number ='$number' $start,$per_page";
that $date and $number variables are undefined variables
I solved the problem, the solution was to remove the pagination page.php file and to add a simple jquery pagination plugin inside the main page, which mean its not necessary to define the post data again.
I'd highly recommend you move from mysql_* to mysqli because you are vulnerable.
$select_table = "select * from `pagination` where `date` = '".$date."' and `number` ='".$number."' $start,$per_page";
I see an extra = in there at the very least, it is also not concatenated properly. I'm not sure what you are trying to do here $start,$per_page";. Also make sure you are escaping your fields and tables with back ticks.
Related
I am trying to pass the ID of the clicked image to next page. When I developed my code, it didn't redirect me to the next page. When I click F12 and check the POST in network, it shows that the variable is passed correctly to the next page as shown in the attached image but it didn't redirect me to the next page. So now I know that the variable is passed and received correctly in the next page but I need what needed in my code to direct me to the next page,
Note: when I tried to put window.location.href = 'userevent.php'; it redirect me but without the variable and gives me error (Notice: Undefined index: clicked in)
Also when I use url: '#userevent.php.Action("delivery", "service")',, it gives me network status 403
this is my code:
<?php
session_start();
require "init.php";
login();
?>
<html>
<!--...-->
<head>
<meta charset="utf-8">
<title> Ghost </title>
<!-- <link rel="Stylesheet" href="css/style1.css">-->
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script >
function myFunction(clicked) {
document.getElementById('test').innerHTML = clicked;
$.ajax({
type: "POST",
//url: '#userevent.php.Action("delivery", "service")',
url: 'userevent.php',
dataType:'json',
data: {"clicked": clicked},
success: function(data){
}
});
window.location.href = 'userevent.php';
}
</script>
</head>
<body>
<div class="sidenav">
Main Page
About Us
</div>
<div class="login-box">
<h1>Add Event</h1>
<div>
<p id="test"> </p>
<?php
// LOGIN USER
function login(){
global $con;
global $counter;
echo "<table align='center' >";
//$email = $mysqli->escape_string('');
$query="SELECT * FROM events ORDER BY ID ASC";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "User with that ID doesn't exist!";
else { // User exists
$counter = 0;
$emptyArray = [];
while($row = $result->fetch_assoc())
{
$emptyArray[$counter]= $row["ID"];
if($counter == 0)
{
echo '<tr>';
}
echo '<td><img id=' . $row["ID"]. ' onClick="myFunction(this.id)" src="images/' . $row["photo"]. '" width="250px" height= "250px" alt="Avatar" >
<h1 id = "GFG_DOWN" style =
"color:white;text-align:center; font-size: 20px; font-weight: bold;"> '.$emptyArray[$counter].'
</h1> </td>';
$counter++;
if($counter == 3)
{
echo "</tr>";
$counter = 0;
}
}
}
}
mysqli_close($con);
?>
and this is the code in the second page:
<div class='textbox'>
<label> ID: ".$_POST['clicked']."</label>
</div>
The entire point of Ajax is that that request is made with JavaScript and the response is handled by JavaScript without navigating to a new page.
If you want to make a POST request and navigate to the resulting page, then use a <form>
window.location.href = 'userevent.php';
it redirect me but without the variable
Assigning a URL to location.href triggers browser navigation (with a GET request) to that URL.
It is a completely different request to the Ajax request so it doesn't have the data from that request.
Again: Use a form for this.
I read the data from database and I get the clicked id of the images.
Put the data you want to send in a submit button instead.
<form method="POST" action="userevent.php">
<?php while($row = $result->fetch_assoc()) ?>
<button name="clicked" value="<?php echo htmlspecialchars($row["ID"]); ?>">
<img src="images/<?php echo htmlspecialchars($row["photo"]); ?> alt="Put useful and unique alt text so people know what they are selecting if they can't see the image">
</button>
<?php } ?>
</form>
I think you are better off making a small form, since you want to send the user to a new page when clicking.
<?php while($row = $result->fetch_assoc()) ?>
<form action="userevent.php" method="POST">
<input type="hidden" name="clicked" value="$row["ID"]">
<img src="images/{{ $row['photo'] }}" class="img">
</form>
<?php } ?>
$('.img').click(function() {
this.form.submit();
});
*Edited to reflect your current edits.
I have a pagination that works correctly even I have added a filter to paginate more rows on the same page is to say that through the filter I can show 10 or 50 rows.
The small defect that I have in my code is that the page is reloaded, changing how many rows show and the same happens in the buttons of the pagination.
This is my code, everything is working on the same page index2.php.
<div id="wrapper">
<div class="container">
<div id="news-header" class="bootgrid-header container-fluid">
<div class="row">
<div class="col-sm-12 actionBar">
<div class="search-bar">
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="What are you looking for?">
</div>
<div class="actions btn-group">
<?php
$select_quantity = '';
if (isset($_POST['amount_show'])) :
$select_quantity = $_POST['amount_show'];
endif;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="amount_show" name="amount_show" onchange="this.form.submit()">
<option value="10" <?php if ($select_quantity==10) echo "selected"; ?>>10</option>
<option value="25" <?php if ($select_quantity==25) echo "selected"; ?>>25</option>
<option value="50" <?php if ($select_quantity==50) echo "selected"; ?>>50</option>
<option value="100" <?php if ($select_quantity==100) echo "selected"; ?>>100</option>
</select>
</form>
</div>
</div>
</div>
</div>
<?php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_POST['amount_show'])) :
$records_by_page = $_POST['amount_show'];
else :
$records_by_page = 10;
endif;
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
echo '<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
echo '</tbody>';
echo '</table>';
$stmt->close();
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
echo '<div class=pagination>
<ul class="pagination">';
if ($prev > 0) :
echo "<li><a href='index2.php?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='index2.php?page=$prev'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class=active>". $page . "</a></li>";
else :
echo "<li><a href='index2.php?page=$i'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a href='index2.php?page=$next'><i class='icon-angle-right'></i></a></li>";
echo "<li><a href='index2.php?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
else :
$stmt->close();
endif;
?>
</div>
</div>
While searching the web I found an ajax code, but sincerely, I did not manage the use ajax or javascript / jquery code.
You can explain how to implement this ajax code or how to avoid the small defect of reloading the page.
<script type="text/javascript">
$(document).ready(function() {
$('.pagination li a').on('click', function(){
/*$('.items').html('<div class="loading"><img src="images/loading.gif" width="70px" height="70px"/><br/>Loading...</div>');*/
$('.items').html('<div class="loading">Loading...</div>');
var page = $(this).attr('data');
var dataString = 'page='+page;
$.ajax({
type: "GET",
url: "ajax.php",
data: dataString,
success: function(data) {
$('.items').fadeIn(2000).html(data);
$('.pagination li').removeClass('active');
$('.pagination li a[data="'+page+'"]').parent().addClass('active');
}
});
return false;
});
});
</script>
This is how my code works, as shown in the following image:
Ajax is going to update information on your page without reloading your page. We want to separate the data from the HTML so we can change which data we're seeing. We can't do that if PHP is the tool writing the data into the HTML. So I recommend separating index2.php into several files. This example uses JSON.
Collect the data
ajax.php
<?php
$data_rows = array();
for ($i = 0; $i < 1000; $i++) {
$data_rows[] = array(
"id" => "id_$i",
"title" => "title_$i",
"description" => "description_$i",
);
}
echo json_encode($data_rows, JSON_PRETTY_PRINT);
This is an example of some junk data, I don't know what data you need. The important thing here is to make an associative array of all the information you want, json_encode() the array, and then echo it. It's important that this is the only thing that gets echoed or printed! This won't work if you have anything else printing in this script.
Edit:
ajax.php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_POST['amount_show'])) :
$records_by_page = $_POST['amount_show'];
else :
$records_by_page = 10;
endif;
$sql = "SELECT id, title, description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$result = $con->query($sql);
$data_rows = array();
while ($row = $result->fetch_assoc()) {
$data_rows = $row;
}
echo json_encode($data_rows, JSON_PRETTY_PRINT);
Your original code includes this mysqli connection, this is data that I don't have access to so I can't test the efficacy of this script. However, this should present all of the data that you're asking about.
Ajax with jQuery
script.js
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ajax.php",
dataType: "json",
success: function(data) {
tableRows = '';
for (let i = 0; i < data.length; i++) {
tableRows += `
<tr>
<td>${data[i].id}</td>
<td>${data[i].title}</td>
<td>${data[i].description}</td>
<td>Edit<td>
</tr>`;
}
$("#tbody-insert").html(tableRows);
}
});
});
Set the url parameter of your ajax call to the name of the php file that's delivering the data. In the example I'm using JSON, it's important to set dataType: "json". jQuery will automatically parse this for you. You can see in the success parameter, data is the name of the php array we've created. I used a simple for loop to create a bunch of table rows, then inserted them into a table body that I've labeled with id="tbody-insert".
Present the data
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tbody-insert">
</tbody>
</table>
I've taken all the PHP out of your index page, it's not very flexible and it requires reloading the entire page before updating the information. The important points to note are the script tags, you need to include jQuery and you need to include the script.js. You also need to have an id for the table body that we're inserting information into. You can wrap your ajax in a function that gets called every time you want to paginate, and query ajax.php for different pages. I don't know the structure of your data so I can't help any further with that.
Let's start with the reason that causes your page to reload: The default browser actions. Several html elements cause the browser to navigate away from the current page. The ones we are concerned in this case are:
#amount_show form submission (the onchange function) that sends the new value via POST request.
The paginator itself (with a links) that tells the php script which records to retrieve via GET request.
Both values should be passed to the php script for it to be able to return the correct records, otherwise the amount parameter would be the default in the php script even if we have a different value selected. To be able to do that, we have to change the passing of the amount variable to a GET request.
Also, when changing the amount value we'll default to the first page to avoid recalculating the page number.
Since the pagination links can therefore change dinamically, I'm not going to handle them in javascript but in php instead, since we already have a template and the calculations. This will make things easier to change down the line.
Let's tackle the javascript first:
$(document).ready(function() {
// When we change the value of the select...
// evt contains the information about the event:
// element receiving the action, the action itself, etc.
$('#amount_show').change(function(evt) {
// Cancel the default browser action
evt.preventDefault()
// Get the target url of the form (our php script)
url = $(this).parent().attr('action')
// Call the funtion that will be doing the request
ajaxLoad(url)
});
// When we click a pagination link... (Explanation below)
$('.items').on('click', '.pagination li a', function(evt) {
evt.preventDefault()
url = $(this).attr('href')
ajaxLoad(url)
});
// Do the actual request
function ajaxLoad(url) {
// How many records do we want to show ?
query_params = {
amount_show: $('#amount_show').val()
};
// Show an indication that we are working
$('.items').html('<div class="loading">Loading...</div>')
$.ajax({
type: "GET",
url: url, // Call php, it will default to page 1 if there's no parameter set
// When calling a link with a page parameter this will be smart
// enough to append the variable to the query string correctly
data: $.param(query_params),
// Handle the data return. In a perfect world, this is always successful
success: function(data) {
// Insert the data in the document.
$('.items').fadeOut('1000', function() { $(this).html(data) }).fadeIn('1000')
}
});
}
});
The line $('.items').on('click', '.pagination li a', function(evt) { attaches a delegate event listener to the .items element that will respond to the click events received by .pagination li a. The reason to do this instead of attaching directly to the element itself is two-fold:
Reduce the number of elements that we have to loop and attach a listener to.
Handle dynamic insertion of elements. When switching content, we are deleting the elements from the document, and their listeners with them. We would have to attach them again on every page load, otherwise with no listeners attached they would go back to the default action. But since this element doesn't change we won't have to do it.
Now for the php. Since you are interested in using a single file, I'm just going to move things around but it will (mostly) be what you have now.
Note: I may have misunderstood what you mean by having all in a single page. If this is a partial template that you are including from your main index, you'll have to change the link targets and action for the form to point to it, adjust some javascript selectors and you could skip the whole ajax request checking.
Main changes:
Remove your onchange function call.
Change POST parameter to GET parameter.
Add a .items span to insert the elements in since it doesn't exist.
Determine if a page load is an ajax load or a regular one using X-Requested-With header. An alternative to this is returning a full response anyway and filtering it with jQuery.
<?php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_GET['amount_show'])) :
$records_by_page = $_GET['amount_show'];
else :
$records_by_page = 10;
endif;
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
// Start capturing the output
ob_start();
?>
<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
$stmt->close();
?>
</tbody>
</table>
<div class=pagination>
<ul class="pagination">
<?php
// When requesting an out-of-bounds page, this won't execute resulting in
// a blank page with no paginator
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
if ($prev > 0) :
echo "<li><a href='" . $_SERVER['PHP_SELF'] . "?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='" . $_SERVER['PHP_SELF'] . "?page=$prev'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class='page-link active' >". $page . "</a></li>";
else :
echo "<li><a class='page-link' href='" . $_SERVER['PHP_SELF'] . "?page=$i'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a class='page-link' href='index2.php?page=$next'><i class='icon-angle-right'></i></a></li>";
echo "<li><a class='page-link' href='index2.php?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
// Get the output into a variable
$results_table = ob_get_clean();
else :
$results_table = "<div>No results found</div>";
$stmt->close();
endif;
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) :
// If is an ajax request, output just the result table and exit
echo $results_table;
die;
endif;
// Print the whole page if its not an ajax request
?>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'/>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js' />
<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css' type='text/css' />
<div id='wrapper'>
<div class='container'>
<div id='news-header' class='bootgrid-header container-fluid'>
<div class='row'>
<div class='col-sm-12 actionBar'>
<div class='search-bar'>
<input type='text' id='myInput' placeholder='What are you looking for?'>
</div>
<div class='actions btn-group'>
<form action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
<select id='amount_show' name='amount_show'>
</select>
</form>
</div>
</div>
</div>
</div>
<span class='items'>
<?php echo $results_table; ?>
</span>
</div>
</div>
For completeness, the alternative method without separating the responses with php, is to filter the response with jQuery by doing the following in the ajax success callback (fades omitted):
results_table = $(data).find('.items').html()
$('.items').html(results_table)
This converts the response from the server into a jQuery object and allows to apply filtering functions as normal. We extract the content we are interested in (content of items: result table and pagination), then we just append it to the items container on our existing page.
UPDATE: I've posted a simplified example without database-related code here. I think there's something weird going on when copy&paste'ng code from/to the editor.
References
DOM events
jQuery ajax and helper functions
PHP output buffering
Not receiving X_REQUESTED_WITH request header
Fade effects in ajax callback
There's no point to start playing with jquery and async calls if even pure html is bit over the limit. In initial code you are mixing POST and GET, use just one.
<div id="wrapper">
<div class="container">
<div id="news-header" class="bootgrid-header container-fluid">
<div class="row">
<div class="col-sm-12 actionBar">
<div class="search-bar">
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="What are you looking for?">
</div>
<div class="actions btn-group">
<?php
//getting both - page and record_by_page from GET
$records_by_page = isset($_GET['amount_show'])?$_GET['amount_show']:10;
$page = isset($_GET['page'])?$_GET['page']:1;
//put page value into form to send it together with amount_show
?>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="amount_show" name="amount_show" onchange="this.form.submit()">
<option value="10" <?php if ($records_by_page==10) echo "selected"; ?>>10</option>
<option value="25" <?php if ($records_by_page==25) echo "selected"; ?>>25</option>
<option value="50" <?php if ($records_by_page==50) echo "selected"; ?>>50</option>
<option value="100" <?php if ($records_by_page==100) echo "selected"; ?>>100</option>
</select>
<input type="hidden" id="page" name="page" value="<?php echo $page; ?>"></input>
</form>
</div>
</div>
</div>
</div>
<?php
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
echo '<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
echo '</tbody>';
echo '</table>';
$stmt->close();
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
echo '<div class=pagination>
<ul class="pagination">';
//add amount_show to each request
if ($prev > 0) :
echo "<li><a href='pagination.php?page=1&amount_show=$records_by_page'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='pagination.php?page=$prev&amount_show=$records_by_page'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class=active>". $page . "</a></li>";
else :
echo "<li><a href='pagination.php?page=$i&amount_show=$records_by_page'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a href='pagination.php?page=$next&amount_show=$records_by_page'><i class='icon-angle-right'></i></a></li>";
echo "<li><a href='pagination.php?page=$total_page&amount_show=$records_by_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
else :
$stmt->close();
endif;
?>
</div>
</div>
I am trying to fix this issues from last two days but :(
Now I have a index.php page where I am displaying all the data of adds from database.
this is my index page
<html>
<head>
<script>
$(document).ready(function(){
var overlayclass = $("<div id='overlayclass'></div>");
//pagination starts
$("#pagination li:first")
.css({'color' : '#FF0084'}).css({'border' : 'solid #dddddd 10px'});
$("#page").load("Controller/pagination_data_all_adds.php?page=1");
//Pagination Click
$("#pagination li").click(function(){
//CSS Styles
$("#pagination li")
.css({'color' : '#FF0084'})
.css({'border' : 'none'});
$(this)
.css({'border' : 'solid #dddddd 10px'})
.css({'color' : '#0063DC'});
//Loading Data
var pageNum = this.id;
$("#page").load("Controller/pagination_data_all_adds.php?page=" + pageNum);
});
//pagination ends
//for closing the div
$(".close").click(function () {
$(".divpopup").hide();
overlayclass.appendTo(document.body).remove();
return false;
});
//for close image
$(".x").click(function () {
$(".divpopup").hide();
overlayclass.appendTo(document.body).remove();
return false;
});
//onclick on button display div and overlay with button value and post the value to the index page where I can use it to select the specific adds data from database
$(':submit').live('click',function () {
var id = $(this).val();
overlayclass.show();
overlayclass.appendTo(document.body);
$(".divpopup").show('slow');
$.ajax({
url: 'index.php',
data:'button=' + $(this).val(),
dataType: 'json',
succss: function(data)
{
$('.divpopup').html('');
alert(data);
$('.divpopup').append('button:'+data);
}
});
return false;
});
});
</script>
</head>
<body>
<div class="divpopup">
<div class="divcontent">
<img src="http://www.catalyst-gc.com/images/icon_close_window.jpg" alt="icon_close_window"
class="x" id="imgclose" />
<div class="detail_data">
<?php
print "<h1>".$button."</h1>";
?>
</div>
Close
</div>
</div>
<div id="page"></div>
<ul id="pagination">
<?php
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'"-->'.$i.'';
}
?>
</ul>
<!--Pagging display ends -->
</body>
</html>
This is my pagination_data_all_adds page which will be load through jQquery load function in index page. inside page div. and the button which is inside table will be click to display the popupdiv with id of adds and than I will use it to display the rest of the data.
<?php include_once('dbconn.php');
$per_page = 6;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$sql = "select * from adds order by add_id limit $start,$per_page";
$result = mysql_query($sql);
echo "<table cellspacing='0'>";
echo "<thead>";
echo "<th></th>";
echo "<th>Advertise</th>";
echo "<th>Title</th>";
//echo "<th>Description</th>";
echo "<th>Price</th>";
echo "</thead>";
while ($adds = mysql_fetch_array($result)) {
echo "<tbody>";
echo "<tr class='even'>";
$image_link = $adds["image"];
echo "<td><img class='image' src=adds_images/".$image_link."></td>";
echo "<td><b>".$adds["add_type"] . "</b></td>";
echo "<td><b>".$adds["add_title"] ."</b></td>";
echo "<td><b>".$adds["add_price"] ."</b></td>";
echo "<td>";
echo "<form method='post' action=''>"
echo "<button class='button' value='".$adds['add_id']."' type='submit'>Detail!</button>";
echo "</form>";
echo"</td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";?>
Now the problem is when I click on the button which is page div it display nothing but when I look at Firebug response it shows there. It does not display when I click the button.
Your dataType in ajax call is json.
$.ajax({
url: 'index.php',
data:'button=' + $(this).val(),
dataType: 'json', <--------------------------------- JSON
But you are returning html.
echo "<table cellspacing='0'>";
echo "<thead>";
echo "<th></th>";
echo "<th>Advertise</th>";
..........................
..........................
Hence your call is actually failing (Which you could have spotted had you used fail).
So answer is return json or change data type.
N.B.
LOTS AND LOTS OF deprecated function. use .on instead of live. use .done instead of success. use mysqli/pdo instead of mysql.
if($_GET)
{
$page=$_GET['page'];
}
You need to use isset or empty that too on approriate index. $_GET is always set. So checking its existance is futile. You need to check the index. i.e.
if(isset($_GET['page']))
again echoing what #itachi has said, pass json data from your php. your js script is waiting for json object yet you passing html file.
to use your code the way it is comment out this line from your JavaScript //dataType: 'json',.
i would also encourage you to use jquery dataTables to save time. take a look at it here
sorry if the title is a little.. vague i couldnt pin it down.
So i am developing a friend request system which works i guess similar in concept to facebook. So you get a request and it lists them without a page reload.
However i get the div 'refreshing' or so i think i cant test the php which is where i have a problem, i will post the relevent code and files below.
It may look a little long winded but it shouldnt be too bad in reality. My php code should keep executing the query which is looking at the database in the updateFriendBox.php however it doesnt seem to be doing this. My code may be messy as well so I apologise.
myaccount.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function refreshDiv()
{
$.get('updateFriendBox.php', function(data){$('#refresh').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, 5000);
});
function box(x){
if($('#'+x).is(":hidden")){
$('#'+x).slideDown(200);
} else {
$('#'+x).hide();
}
}
</script>
<?php
$addBox = '<div style="display:inline; padding:5px;">
Show/Hide Friend Requests
</div>';
// a bit further down in the code where its all called:
<? echo $addBox; ?></span>
<div class="friendSlide" id="fRequ" style="height:240px; overflow:auto;">Your friend requests: <br />
<div id="refresh"> <?php // this is where the refresh call is ?>
</div>
</center>
</div>
</div>
</div>
updateFriendBox.php:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function acceptFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "acceptFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
function denyFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "denyFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
</script>
</head>
<body>
<?php
include 'dbc.php';
$sql = "SELECT * FROM friendRecu WHERE mem2='" . $_SESSION['user_id'] . "' ORDER BY id ASC LIMIT 10";
$query = mysql_query($sql)or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1) {
echo "No friend requests";
} else {
while($row = mysql_fetch_array($query)){
$requestID = $row['id'];
$req = $row['mem1'];
$sqlName = mysql_query("SELECT full_name FROM users WHERE id='$req'");
while($row = mysql_fetch_array($sqlName)){
$requesterName = $row['full_name'];
}
echo '<hr /><table width="100%", cellpadding="5"><tr><td width="17%" align="left"><div style="overflow:hidden; height:50px; color:white;"></div></td> <td width="83%">' . $requesterName . ' added you as a friend
<span id="req' . $requestID . '">
Accept
||
Deny
</span></td></tr>
</table>';
}
}
?>
I think you are having a problem because your updateFriendBox.php is returning too much. Remove all that inline JS code, place it in an include file, and include it from myaccount.php. You also shouldn't have <head> and <body> sections in your updateFriendBox.php file.
The ajax call here doesn't create a whole new page, you're getting additional HTML to add to the original page.
So the only thing you should have there is your SQL query, the loop, and your HTML output for each data row.
I am trying to make my pagination script a bit more dynamic and am needing some help with the calculating of the page numbers part.
I have this script below which calculates the number of pages using php, however I would like to add other buttons that when clicked will filter and sort out data which means the pagination numbers need to be calculated again.
The script I have does not allow for this to happen, so I am wondering if there is a more efficient/dynamic way of calculating the pagination numbers then the way I am doing it now.
This is the main page (pagination.php)
<?php
include('config.php');
$per_page = 3;
//Calculating no of pages
$sql = "select * from explore";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1`` /jquery.min.js"></script>
<script type="text/javascript" src="jquery_pagination.js"></script>
<div id="loading" ></div>
<div id="content" data-page="1"></div>
<ul id="pagination">
<?php
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li class="page_numbers" id="'.$i.'">'.$i.'</li>';
}
?>
</ul>
<br />
<br />
And here is the JS script (jquery.pagination.js)
$(document).ready(function(){
//Display Loading Image
function Display_Load()
{
$("#loading").fadeIn(900,0);
$("#loading").html("<img src='bigLoader.gif' />");
}
//Hide Loading Image
function Hide_Load()
{
$("#loading").fadeOut('slow');
};
//Default Starting Page Results
$("#pagination li:first").css({'color' : '#FF0084'}).css({'border' : 'none'});
Display_Load();
$("#content").load("pagination_data.php?page=1", Hide_Load());
//Pagination Click
$("#pagination li").click(function(){
Display_Load();
//CSS Styles
$("#pagination li")
.css({'border' : 'solid #dddddd 1px'})
.css({'color' : '#0063DC'});
$(this)
.css({'color' : '#FF0084'})
.css({'border' : 'none'});
//Loading Data
var pageNum = this.id;
$("#content").load("pagination_data.php?page=" + pageNum, function(){
Hide_Load();
$(this).attr('data-page', pageNum);
});
});
});
I tried to put the calculation part of the script in 'pagination_data.php' file so when I clicked a button or link to go to that page it would generate everything, but it did not work.
So, any help on figuring out a good way of doing this would be great. Thanks.
Your page generation code is fine, it's the fixed query that it's using that needs to be changed. I would suggest changing your pagination code into a function that takes an $sql parameter so that you could pass in the correct query adjusted by any filters:
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>';
}
}
and then call it like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1`` /jquery.min.js"></script>
<script type="text/javascript" src="jquery_pagination.js"></script>
<div id="loading" ></div>
<div id="content" data-page="1"></div>
<ul id="pagination">
<?php generate_pagination('SELECT * FROM explore'); ?>
</ul>
<br />
<br />
or with a filter:
<?php generate_pagination('SELECT * FROM explore WHERE key="value"'); ?>