I would like to add pagination to my existing table which I have programmed using ajax.
I have tried multiple pagination solutions and none of them looks like its compatible with my existing table which I have right now
Table in index.php
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<th width="5%"></th>
<th width="10%">Serial No.</th>
<th width="20%">Equipment Type</th>
<th width="15%">Document Remarks</th>
<th width="10%">Supplier</th>
<th width="10%">Date In</th>
<th width="10%">Customer</th>
<th width="10%">Date Out</th>
</thead>
<tbody></tbody>
</table>
</div>
Script for showing table in index.php
<script>
$(document).ready(function () {
function fetch_data()
{
$.ajax({
url: "select.php",
method: "POST",
dataType: "json",
success: function (data)
{
var html = '';
for (var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" value="' +
data[count].id + '" id="' + data[count].id + '" data-serial_number="' +
data[count].serial_number + '" data-equipment_type="' +
data[count].equipment_type + '" data-document_remarks="' +
data[count].document_remarks + '" data-supplier="' + data[count].supplier +
'" data-date_scan="' + data[count].date_scan + '" data-customer="' +
data[count].customer + '" data-date_out="' + data[count].date_out + '"
class="check_box" /></td>';
html += '<td>' + data[count].serial_number + '</td>';
html += '<td>' + data[count].equipment_type + '</td>';
html += '<td>' + data[count].document_remarks + '</td>';
html += '<td>' + data[count].supplier + '</td>';
html += '<td>' + data[count].date_scan + '</td>';
html += '<td>' + data[count].customer + '</td>';
html += '<td>' + data[count].date_out + '</td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
}
</script>
select.php
include('database_connection.php');
$query = "SELECT * FROM inventory ORDER BY id DESC";
$statement = $connect->prepare($query);
if ($statement->execute()) {
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
}
?>
In your fetch_data() function you will need to include page data in your POST request:
limit should be the number of items viewable per page
offset should be limit multiplied by the page number (starting at 0)
Ex. below would request the second page of results (10 results per page)
$.ajax({
url: "select.php",
method: "POST",
dataType: "json",
data: {limit: 10, offset: 10},
// etc.
The in your PHP script you will need to read these variables and add them to your query:
$limit = $_POST['limit'];
$offset= $_POST['offset'];
$query = "SELECT * FROM inventory ORDER BY id DESC LIMIT = ? OFFSET= ?";
$statement = $connect->prepare($query);
if ($statement->execute([$limit, $offset])) {
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
}
Related
I'm trying to display data from my PostgreSQL into an HTML table using Ajax and PHP. But it seems that the data I am getting is not binding into the columns element of HTML table, I just get back a Json string .
How can I am binding id, employee_name, employee_salary and employee_age column with 'td' element of HTML table
This is my code:
HTML
<div class="col-sm-6" style="padding-top:50px;">
<table id="employee_grid" class="table" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tbody id="emp_body">
</tbody>
</table>
</div>
Ajax (binding column with element of HTML table):
$(document).ready(function(){
/* Handling get employee */
function get_employee() {
$.ajax({
type : 'GET',
url : 'response.php?action=list',
success : function(response){
response = JSON.parse(response);
var tr;
$('#emp_body').html('');
$.each(response, function( index, emp ) {
tr = $('');
tr.append("" + emp.id + "");
tr.append("" + emp.employee_name + "");
tr.append("" + emp.employee_salary + "");
tr.append("" + emp.employee_age + "");
var action =
"<div class='btn-group' data-toggle='buttons'>";
action += "<a href='#' target='_blank' class='btn btn-warning btn-xs' data-toggle='modal' data-target='#edit_model'>Edit</a>";
action += "<a href='#' target='_blank' class='btn btn-danger btn-xs'>Delete</a></div>";
tr.append(action);
$('#emp_body').append(tr);
});
}
});
}
//initialize method on load
function init() {
get_employee();
}
init();
});
PHP (query data from PostgreSQL)
<?php
include("connection.php");
$params = $_REQUEST;
$action = isset($params['action']);
$params['action'] !='' ? $params['action'] : 'list';
$empCls = new Employee();
switch($action) {
case 'list':
$empCls->getEmployees();
break;
default:
return;
}
class Employee {
protected $conn;
protected $data = array();
function __construct() {
$db = new dbObj();
$connString = $db->getConnstring();
$this->conn = $connString;
}
function getEmployees() {
$sql = "SELECT * FROM employee";
$queryRecords = pg_query($this->conn, $sql) or die("error to fetch employees data");
$data = pg_fetch_all($queryRecords);
echo json_encode($data);
}
}
?>
You need add <tr> & <td> tag as well while appending the responses to your table.
Changes you can add in your current code :
var tr = $('<tr></tr>'); //tr tag
//appending td >>
tr.append("<td>" + emp.id + "</td>");
tr.append("<td>" + emp.employee_name + "</td>");
tr.append("<td>" + emp.employee_salary + "</td>");
tr.append("<td>" + emp.employee_age + "</td>");
Demo Code :
var response = [{
"id": 1,
"employee_name": "xyz",
"employee_salary": 3444,
"employee_age": 23
},
{
"id": 2,
"employee_name": "xyz2",
"employee_salary": 34442,
"employee_age": 9
},
{
"id": 3,
"employee_name": "xyz3",
"employee_salary": 34443,
"employee_age": 2
}
] //this is dummy data
$(document).ready(function() {
/* Handling get employee */
function get_employee() {
/* $.ajax({
type: 'GET',
url: 'response.php?action=list',
success: function(response) {
response = JSON.parse(response);*/
$('#emp_body').html('');
$.each(response, function(index, emp) {
var tr = $('<tr></tr>'); //tr tag
//appending td >>
tr.append("<td>" + emp.id + "</td>");
tr.append("<td>" + emp.employee_name + "</td>");
tr.append("<td>" + emp.employee_salary + "</td>");
tr.append("<td>" + emp.employee_age + "</td>");
var action =
"<td><div class='btn-group' data-toggle='buttons'>";
action += "<a href='#' target='_blank' class='btn btn-warning btn-xs' data-toggle='modal' data-target='#edit_model'>Edit</a>";
action += "<a href='#' target='_blank' class='btn btn-danger btn-xs'>Delete</a></div></td>";
tr.append(action);
$('#emp_body').append(tr);
});
/*}
});*/
}
//initialize method on load
function init() {
get_employee();
}
init();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" style="padding-top:50px;">
<table id="employee_grid" class="table" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody id="emp_body">
</tbody>
</table>
</div>
I am trying to add pagination links in my view but can't use "$data->links()" because I've passed data in my ajax and response in table tbody. Also, I would be appreciated if you could help me to complete my pagination according to my current structure.
function getAllUsers() {
$.ajax({
url: base_url + '/users/listing',
method: 'GET',
success: function(result) {
var html = '';
$.each(result.data, function(i, row) {
html += '<tr>'
html += '<td class="text-center">' + ++i + '</td>'
html += '<td>' + row.name + '</td>'
html += '<td>' + row.email + '</td>'
html += '<td>' + row.phone + '</td>'
html += '<td>' + row.created_at + '</td>'
html += '<td class="text-center"><ul class="table-controls">'
html += '<li></li>'
html += '<li></li>'
html += '</ul></td>'
html += '</tr>';
})
$('table tbody').html(html)
}
});
}
// Routes
Route::get('/users', 'Backend\UserController#index')->name('users');
Route::get('/users/listing', 'Backend\UserController#listing');
//Controller
public function index() {
return view('backend/users/listing');
}
public function listing() {
$users=User::paginate(5);
return $users;
}
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped table-checkable table-highlight-head mb-4">
<thead>
<tr>
<th class="text-center">No.
</th>
<th class="">Name</th>
<th class="">Email</th>
<th class="">Phone</th>
<th class="">Register at</th>
<th class="text-center">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
When using the ->paginate() helper in your model, you don't only get the data, you get the urls for next and previous links as well on the response:
{
....
"first_page_url": "http://laravel.app?page=1",
"last_page_url": "http://laravel.app?page=4",
"next_page_url": "http://laravel.app?page=2",
"data": ....
}
So, your success function should look similar to this:
success: function(result) {
var html = '';
var nextlink = result.next_page_url;
$.each(result.data, function(i, row) {
....
}
}
Table data is not cleared after each ajax call. New data is appended below the previous data
$('#show_data').remove();
I have tried this but its not working
View
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Date</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
<tbody id="show_data">
</tbody>
</table>
Script
<script>
$(document).ready(function () {
//Date picker
$('#datepicker').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
});
$("#datepicker").attr("autocomplete", "off");
$(document).on('submit','#myform',function(){
event.preventDefault();
var date = $('#datepicker').val();
console.log(date);
$('#show_data').remove();
$.ajax({
type:"POST",
url:"<?php echo base_url().'admin/Dashboard/get_blog'; ?>",
data:{date:date},
dataType: "json",
success:function(data) {
console.log(data[0].blog_id);
let i;
for(i=0;i<data.length;i++){
$('#show_data').append('<tr><td>' + data[i].article_name + '</td>' +
'<td>' + data[i].description + '</td>' +
'<td>' + data[i].date + '</td>' +
'<td>' + data[i].time + '</td>' +
'</tr>');
}
},
error: function() {
alert("oops...");
},
});
});
});
</script>
Present Output
Input-> 2019-05-25 -> Submit
Output-> Data 1
Data 2
Input-> 2019-05-24 -> Submit
Output-> Data 1
Data 2
Data 3
Expected Output
Input-> 2019-05-25 -> Submit
Output-> Data 1
Data 2
Input-> 2019-05-24 -> Submit
Output-> Data 3
Its because you append your response to previous data. Try this way
$.ajax({
type:"POST",
url:"<?php echo base_url().'admin/Dashboard/get_blog'; ?>",
data:{date:date},
dataType: "json",
success:function(data) {
console.log(data[0].blog_id);
let i;
let html= '';
for(i=0;i<data.length;i++){
html += '<tr><td>' + data[i].article_name + '</td>' +
'<td>' + data[i].description + '</td>' +
'<td>' + data[i].date + '</td>' +
'<td>' + data[i].time + '</td>' +
'</tr>');
}
$('#show_data').html(html);
},
error: function() {
alert("oops...");
},
});
You can try change code
$('#show_data').remove();
to
$('#show_data').empty();
empty() function will clear content of the element. Docs is here https://api.jquery.com/empty/
For report generation in the project I made I want to use 2 methods:
By date range (from date and up to date)
By employee ID
While using the above keywords the complete record of the employee should be displayed in that particular range.
For ex- emp1234 is the employee whose record is to be checked between date 20 may 2018 to 30 june 2018. The result must be displayed in between the range
Another thing is that the search can be done either by date or by employee id or both but both should not be compulsory.
the script is as follows:
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#report_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#report_table').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
I need to combine these two different queries into one.
filter.php
<?php
//filter.php
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost", "root", "", "ais");
$output = '';
$query = "
SELECT * FROM tbl_employees,tbl_in_time_attendance,tbl_out_time_attendance WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date AND tbl_in_time_attendance.date AND tbl_out_time_attendance.date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'
";
$result = mysqli_query($connect, $query);
$cnt=1;
$output .= '
<table class="table table-bordered">
<tr>
<th width="6%">Sr No.</th>
<th width="15%">EMPLOYEE ID</th>
<th width="20%">EMPLOYEE NAME</th>
<th width="15%">IN_TIME</th>
<th width="15%">OUT_TIME</th>
<th width="15%">DATE</th>
<th width="25%">WORKING HOURS</th>
</tr>
';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$outtime = $row["outtime"];
$intime = $row["intime"];
$array1 = explode(':', $intime);
$array2 = explode(':', $outtime);
$minutes1 = ($array1[0] * 60.0 + $array1[1])/60;
$minutes2 = ($array2[0] * 60.0 + $array2[1])/60;
$diff = round(($minutes2 - $minutes1),1).' hrs';
$output .= '
<tr>
<td align="center">'. $cnt .'</td>
<td align="center">'. $row["EmpId"] .'</td>
<td align="center">'. $row["FirstName"] . " " . $row["LastName"].'</td>
<td align="center">'. $row["intime"] .'</td>
<td align="center"> '. $row["outtime"] .'</td>
<td align="center">'. $row["date"] .'</td> ';
if ($diff < 8) {
$output .= '<td align="center" style="background-color: #F42E2E;"> ' . $diff . ' </td>';
} else {
$output .= '<td align="center" style="background-color: #55E443;"> ' . $diff . ' </td>';
}
$output .= '</tr>';
$cnt++;
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Record Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
Fetch.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ais");
$output = '';
if(isset($_POST["query"]))
{
$query = "
SELECT * FROM tbl_employees,tbl_in_time_attendance,tbl_out_time_attendance WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date AND tbl_in_time_attendance.date AND tbl_employees.EmpId LIKE '".$_POST["query"]."' ";
}
else
{
$query = "SELECT * from tbl_employees, tbl_in_time_attendance , tbl_out_time_attendance WHERE tbl_employees.EmpId=tbl_in_time_attendance.EmpId AND tbl_in_time_attendance.EmpId=tbl_out_time_attendance.EmpId AND tbl_in_time_attendance.date=tbl_out_time_attendance.date";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$cnt=1;
$output .= '
<table class="table table-bordered">
<tr>
<th width="6%">Sr No.</th>
<th width="15%">EMPLOYEE ID</th>
<th width="20%">EMPLOYEE NAME</th>
<th width="15%">IN_TIME</th>
<th width="15%">OUT_TIME</th>
<th width="15%">DATE</th>
<th width="25%">WORKING HOURS</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$outtime = $row["outtime"];
$intime = $row["intime"];
$array1 = explode(':', $intime);
$array2 = explode(':', $outtime);
$minutes1 = ($array1[0] * 60.0 + $array1[1])/60;
$minutes2 = ($array2[0] * 60.0 + $array2[1])/60;
$diff = round(($minutes2 - $minutes1),1).' hrs';
$output .= '
<tr>
<td align="center">'. $cnt .'</td>
<td align="center">'. $row["EmpId"] .'</td>
<td align="center">'. $row["FirstName"] . " " . $row["LastName"].'</td>
<td align="center">'. $row["intime"] .'</td>
<td align="center"> '. $row["outtime"] .'</td>
<td align="center">'. $row["date"] .'</td> ';
if ($diff < 8) {
$output .= '<td align="center" style="background-color: #F42E2E;"> ' . $diff . ' </td>';
} else {
$output .= '<td align="center" style="background-color: #55E443;"> ' . $diff . ' </td>';
}
$output .= '</tr>';
$cnt++;
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Record Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
?>
I want these to separate fetch and filter files into one file.
Please help.
please dont delete the question again, i was writing a few minutes and then the question was deleted haha
soo, as you have a filter button which has to be clicked to get the results there are two ways you can choose!
you display your table with datatable plugin which means you only need to filter by date and then write the employeeid in the searchbox and you will only see the results for this person WITHOUT having to query it again!
https://datatables.net/
you get the two dates AND your search query by clicking on the filter button which means you will only have one php file (i dont know why you actually want to use fetch & filter).. In your php file you then look if there are only dates submitted OR the query is also submitted:
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
var query = $("#search_text").val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date, to_date:to_date, employee: query},
success:function(data)
{
$('#report_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
in php file
if(isset($_POST["employee"]) AND $_POST["employee"] != "") {
// make your sql call with dates AND employeeid
} else {
// make your sql call only with dates
}
depending on how many results you have I'm sure its also possible to dont even have to query again for different dates and instead tweak datatable so that you have one from_date, one to_date and one search field and filter the table after keyup.. see example here: https://datatables.net/examples/api/multi_filter.html
I have a foreach statement that is adding the data from a DB to my table rows
HTML
<table id="myTable" class="display table center-table" width="100%" >
<thead>
<tr>
<th>Product #</th>
<th>Alternate #</th>
<th>Description</th>
<th>On Hand</th>
<th>Condition</th>
</tr>
</thead>
<tbody id="productResults"> </tbody>
</table>
PHP
$query = $sql . " limit " . $start . "," . $perPage;
$data = $db_handle->runQuery($query);
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = $db_handle->numRows($sql);
}
$pages = ceil($_GET["rowcount"]/$perPage);
$output = '';
if(!empty($data)) {
$formval = '<input type="hidden" class="pagenum" value="' . $page . '" /><input type="hidden" class="total-page" value="' . $pages . '" />';
foreach($data as $k=>$v) {
$output .= '<tr><td>' . $formval . $data[$k]["wuno_product"] . '</td>';
$formval = '';
$output .= '<td>' . $data[$k]["wuno_alternates"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_description"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_onhand"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_condition"] . '</td></tr>';
}
}
echo $output;
Then in my user view I am adding the data back to the page like this,
JQUERY
<script>
(function($) {
$(document).ready(function(){
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: { rowcount:$("#rowcount").val() },
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){/* convert to dom element */
$("#productResults").append( data.toElement() );
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
if($(".pagenum:last").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum:last").val()) + 1;
getresult('<?php echo $assetPath; ?>?page='+pagenum);
}
}
});
});
})( jQuery );
</script>
But when it shows up in my page it shows up outside of the table and does not have the html added to it. It looks like this in the page,
8855K5MS21026-B2111212M39029/5-1171313Q4559PROD CODE: 4057911RESTOCKING CHARGE11TAS8732-1C277TEST REPORTS6690H549(W) LAMP CKT99MEC-1MF1 FEET DB9M/F CABLE11T1-GMIL-L-25567E1 GAL JUG2121WL-322914VOLT T-1 BULB100100
Which was the data from the DB just all together... Why would this happen and how can I fix it?
It shows up above the table instead.
firstly, you are attempting to add to a table, but the first portion of your generated code is a form element outside the table structure; any modern browser is going to spot the mistake and add in the assumed missing
</table>
which is why the response is outside a table view.