I have one table fetching data from database and displaying on page using PHP. i have created pagination using Ajax,PHP and MySQL. but when i am clicking on the page numbers, some time it is working and some time the table is displaying records on the first page irrespective of the page i clicked.please help me to solve this issue, i am trying since long time to resolve the issue and i could not. My main page is as follows.....
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Load Data without page refresh</title>
<!--<link rel="stylesheet" href="style/css/bootstrap.min.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!--<script src="scripts/js/bootstrap.min.js"></script>-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!--<script src="scripts/js/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Pagintation without page refresh</h3>
<div class="table-responsive" id="pagination_data">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
load_data();
function load_data(page) {
$.ajax({
url: "pagination.php",
method: "POST",
data: {
page: page
},
success: function(data) {
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function() {
var page = $(this).attr("id");
//alert(page);
load_data(page);
});
});
</script>
pagination.php
<?php
//pagination.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$record_per_page = 5;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM tbl_student ORDER BY student_id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["student_name"].'</td>
<td>'.$row["student_phone"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM tbl_student ORDER BY student_id DESC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>
Related
Ik want to build a ajax/jquery page navigation so when the user clicks on a page, the url changes to so that there are no problems with browser's back button. I found a lot of answers for this but not what I searched for. I saw this code below on a tutorial site and I want to customize it so that the url moves to. Do I have to build that in the ajax script of on the PHP side? How can I achieve this?
My index.php
<html>
<head>
<title>Webslesson Tutorial | Make Pagination using Jquery, PHP, Ajax and MySQL</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Make Pagination using Jquery, PHP, Ajax and MySQL</h3><br />
<div class="table-responsive" id="pagination_data">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagina.php",
method:"POST",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
history.pushState({ foo: 'bar' }, '', '/bank'); // I tried this line but it don't work
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
And my pagina.php
<?PHP
$connect = mysqli_connect("hidden", "hidden", "hidden","publiek2") or die("Connection failed: " . mysqli_connect_error());
$record_per_page = 50;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["merk"].'</td>
<td>'.$row["model"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>
Thanks in advance.
I've tried to customize the ajax script.
As a javascript and PHP developer I don't understand much about Jquery but I think the code describes that there is a div called.pagination_link takes id as page number eg: 1. And makes an HTTP POST request to the PHP side. You can simply do this with a sample example in Javascript.
HTML
<div id="1" classname="pagination_link">1</div>
Javascript
const id = document.querySelector('.pagination_link').getAttribute('id');
fetch('pagina.php', {
method : 'POST',
body : id
})
If you want to send data.
I added a hidden text value with the page number as value and called the id 'idd' and recalled that id on the ajax page. It works good now but if I want to go back with browser button, the url moves to the previous page but the results on the page stays te same. How can I resolve that?
My new index.php JS code
<script>
$(document).ready(function(){
var idd;
load_data();
function load_data(page)
{
$.ajax({
url:"pagina.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
if (idd === undefined) {
alert("ja");
idd = 1;
alert(idd);
history.pushState({}, '', 'http://localhost:4612/pagina/1');
}
else {
idd = $("#idd").val();
history.pushState({}, '', 'http://localhost:4612/pagina/'+idd);
}
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
and my altered pagina.php
<?PHP
$connect = mysqli_connect("hidden", "hidden", "hidden","publiek2") or die("Connection failed: " . mysqli_connect_error());
$record_per_page = 50;
$page = '';
$output = '';
if(isset($_GET["page"]))
{
$page = $_GET["page"];
echo "<input type='hidden' id='idd' value='".$_GET['page']."'>";
}
else
{
$page = 1;
$idd = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["merk"].'</td>
<td>'.$row["model"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>
I recently started learning ajax in order to use the live filter by checkbox. This worked out well until i decided to limit the results fetched from the database using order by id asc limit 0,$rowperpage where rowperpage = 3. Adding this to my code disabled the checkbox filter completely. What could i be doing wrong?
The following is my code.
index.php
<?php
//index.php
include('database_connection.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Product filter in php</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<!-- Page Content -->
<div class="">
<h3>Duration</h3>
<?php
$query = "
SELECT DISTINCT(duration) FROM career
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="checkbox">
<label><input type="checkbox" class="common_selector duration" value="<?php echo $row['duration']; ?>" > <?php echo $row['duration']; ?></label>
</div>
<?php
}
?>
</div>
<br />
<div class="filter_data">
</div>
<style>
#loading
{
text-align:center;
background: url('loader.gif') no-repeat center;
height: 150px;
}
.jobs{
background: gray;
margin: 10px;
padding: 10px;
width: 200px;
}
</style>
<script>
$(document).ready(function(){
filter_data();
function filter_data()
//this deals with filter checkboxes
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var duration = get_filter('duration');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, duration:duration},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
});
</script>
</body>
</html>
fetch_data.php
<?php
//fetch_data.php
include('database_connection.php');
$rowperpage = 3;
if(isset($_POST["action"]))
{
//statement limits but disables check box filter
$query = "
SELECT * FROM career order by id asc limit 0,$rowperpage
";
if(isset($_POST["duration"]))
{
$duration_filter = implode("','", $_POST["duration"]);
$query .= "
WHERE duration IN('".$duration_filter."')
";
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<div class="jobs">
Title : '. $row['title'] .' <br />
duration : '. $row['duration'] .'
</div>
';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
?>
database_connection.php
<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=biit", "root", "");
?>
The database table 'career'
Any help will be much appreciated :)
what happen in the code is that everytime i choose in multiple drop down it fetch the data what i want to happen is to click the button first then it will fetch the data...... thank u guys got the code in here https://www.webslesson.info/2018/05/ajax-live-data-search-using-multi-select-dropdown-in-php.html
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=db", "root", "");
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Live Data Search using Multi Select Dropdown in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<script src="js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Multi Select Dropdown in PHP</h2><br />
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<input type="hidden" name="hidden_country" id="hidden_country" />
<div style="clear:both"></div>
<br />
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('tbody').html(data);
}
})
}
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
var query = $('#hidden_country').val();
load_data(query);
});
});
</script>
fetch.php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=dbattendancelibrary", "root", "");
if($_POST["query"] != '')
{
$search_array = explode(",", $_POST["query"]);
$search_text = "'" . implode("', '", $search_array) . "'";
$query = "
SELECT * FROM tbl_customer
WHERE Country IN (".$search_text.")
ORDER BY CustomerID DESC
";
}
else
{
$query = "SELECT * FROM tbl_customer ORDER BY CustomerID DESC";
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row["CustomerName"].'</td>
<td>'.$row["Address"].'</td>
<td>'.$row["City"].'</td>
<td>'.$row["PostalCode"].'</td>
<td>'.$row["Country"].'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5" align="center">No Data Found</td>
</tr>
';
}
echo $output;
?>
It fires an ajax call because of this code:
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
var query = $('#hidden_country').val();
load_data(query);
});
If you want to fire when clicking on a button, you will need to put in HTML for the button first. Then use the id for load_data event, for example you will have a button called '#btn_search':
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
});
$('#btn_search').click(function(e){
e.preventDefault();
var query = $('#hidden_country').val();
load_data(query);
});
Your full HTML above becomes like this:
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=db", "root", "");
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Live Data Search using Multi Select Dropdown in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<script src="js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Multi Select Dropdown in PHP</h2><br />
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<input id="btn_search" type="button" value="Filter" />
<input type="hidden" name="hidden_country" id="hidden_country" />
<div style="clear:both"></div>
<br />
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('tbody').html(data);
}
})
}
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
});
$('#btn_search').click(function(e){
e.preventDefault();
var query = $('#hidden_country').val();
load_data(query);
});
});
</script>
I just want to know how can i fetch the design of the datatables of my table. Because the filter and the pagination of the table is not working. Heres my code.
i have this plugin in my
<link rel="stylesheet" href="../assets/vendor/datatables-bootstrap/dataTables.bootstrap.css">
<link rel="stylesheet" href="../assets/vendor/datatables-fixedheader/dataTables.fixedHeader.css">
<link rel="stylesheet" href="../assets/vendor/datatables-responsive/dataTables.responsive.css">
<link rel="stylesheet" href="../assets/vendor/datatables-bootstrap/dataTables.bootstrap.css">
<link rel="stylesheet" href="../assets/vendor/datatables-fixedheader/dataTables.fixedHeader.css">
<link rel="stylesheet" href="../assets/vendor/datatables-responsive/dataTables.responsive.css">
<script src="../assets/vendor/datatables/jquery.dataTables.min.js"></script>
<script src="../assets/vendor/datatables-fixedheader/dataTables.fixedHeader.js"></script>
<script src="../assets/vendor/datatables-bootstrap/dataTables.bootstrap.js"></script>
<script src="../assets/vendor/datatables-responsive/dataTables.responsive.js"></script>
<script src="../assets/vendor/datatables-tabletools/dataTables.tableTools.js"></script>
display
<div id="table_data" >
</div>
script
fetch_data();
function fetch_data()
{
var action = "fetch";
$.ajax({
url:"table/serviceTypeTable.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#table_data').html(data);
}
})
}
query for fetch:
if(isset($_POST["action"]))
{
if($_POST["action"] == "fetch")
{
$qry = mysql_query("select * from services_type")or die(mysql_error());
$count = mysql_num_rows($qry);
$output = '
<table class="table table-hover dataTable table-striped width-full" data-plugin="dataTable">
<thead>
<th>Services Types</th>
<th>Action</th>
</thead>
';
while($row = mysql_fetch_array($qry))
{
$services_type_id = $row['services_type_id'];
$output .= '
<tbody>
<tr>
<td>'.$row['services_type_name'].'</td>
<td style="text-align:center;">
<i class="fa fa-edit"></i>
</td>
</tr>
</tbody>
';
}
$output .= '</table>';
echo $output;
}
}
my problem is the datatables design is not working. that's all thanks :)
I figured it out. I just put this script in query fetch at the button after the
:)
<script>
$("#table").dataTable({
});
</script>
I trying to addClass to a row $('tr:first-child').next().addClass("current");
Entire html
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>All Rows</title>
<script type="text/javascript" src="jquery.js"></script>
<style type="text/css">
.container {padding-left: 20px; padding-right: 20px;}
.forms{
display:inline-block;
margin-top:2%;
}
.buttons{border:1px solid #708090;}
input {margin-bottom:2%;margin-right:5%;}
button{margin-right:3%;}
.forms{border-top:3px solid #708090;}
.tableholder{height:300px; overflow-y:auto;}
.current{background-color:pink;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$.get("getall.php", function(data){
{
$('.tableholder').append(data);
}
});
$('tr:first-child').next().addClass("current");
$("#next").click(function(){
$("table").find('.current').removeClass("current");
});
});
</script>
</head>
<body>
<div id="sc" class="container">
<div class="tableholder">
</div>
</div>
</body></html>
and my php script.Don't worry about the deprecated mysql functions.We use an old php installation
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "caliban";
$tableName = "caliban";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_assoc($result);
$result = mysql_query("SELECT * FROM $tableName");
$rows = Array();
$i=0;
while($row = mysql_fetch_assoc($result)){
//array_push($rows, $row);
$rows[$i++] = $row;
}
echo "<table id='tab' border='1'>
<thead>
<tr>
<th><form><input type='checkbox' /></form></th>
<th>firstname</th>
<th>lastname</th>
<th>city</th>
<th>continent</th>
</tr>
</thead>
<tbody>";
for($j=0;$j<count($rows); $j++){
$id = $rows[$j]['id'];
$firstname = $rows[$j]['firstname'];
$lastname = $rows[$j]['lastname'];
$city = $rows[$j]['city'];
$continent = $rows[$j]['continent'];
echo
"<tr id='$id' class=''>
<td><input type='checkbox' /></td>
<td>$firstname</td>
<td>$lastname</td>
<td>$city</td>
<td>$continent</td>
</tr>";
}
echo "</tbody>
</table>";
?>
The get is successful and the table displays as it should but the class cannot be applied.Where am i going wrong?.
Try this:
$(document).ready(function () {
$.get("getall.php", function (data) {
$('.tableholder').append(data);
$('tr:first-child').next().addClass("current");
});
$("#tab").on('click','#next',function () {
$("table").find('.current').removeClass("current");
});
});
BTW,IDs must be unique on context page, that means only one element can have the ID 'next'
Here is your code block.
$(document).ready(function(){
$.get("getall.php", function(data){
{
$('.tableholder').append(data);
}
});
$('tr:first-child').next().addClass("current");
The $.get call is asynchronous which means, the script will continue before it's results are returned. Thus,
$('tr:first-child').next().addClass("current");
Is getting called before,
$('.tableholder').append(data);
Try this instead:
$(document).ready(function(){
$.get("getall.php", function(data){
{
$('.tableholder').append(data);
$('tr:first-child').next().addClass("current");
}
});
Your .get() request is asynchronous, so when you're trying to apply that style, there is no table yet. Apply the style after you append the data.
$.get("getall.php", function(data) {
$('.tableholder').append(data);
$('tr:first-child').next().addClass("current");
});