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) {
....
}
}
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>
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/
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);
}
I am using CodeIgniter, I have a form and fields are Employee_name, fromDate, and endDate. I am sending the data to Ajax.(I haven't shared the form code and model code) Now I am displaying the records from database using AJAX and JSON. I am getting the correct output from the database but there is some issue I don't know it's JSON or another issue. I am getting the undefined and then getting my output.
In below image, I am getting the total 9 records from the database which is correct but when I am displaying using JSON then I am getting 18 records. First 9 records undefined and next 9 records my output.
Would you help me out in this issue?
View
<!--form code here-->
<form name="employee_attendance"></form>
<!--end form code here-->
$("form[name='employee_attendance']").validate({
rules: {
employee_Name: {
required: true
},
fromDate: {
required: true
},
toDate: {
required: true
}
},
submitHandler: function(form) {
var employee_Name = $('#employee_Name').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
url: baseUrl + "/Reports_control/report_attendance",
method: "POST",
//dataType: "json",
data: {
employee_Name: employee_Name,
fromDate: fromDate,
toDate: toDate
},
success: function(response) {
$('.search_record tbody tr').hide();
var data = JSON.parse(response);
if (data.status === 'error') {
alert(data.msg);
}
if (data.status === 'success') {
$('.addendence_report_list').show();
var trHTML = '';
$.each(data.records, function(i, o) {
trHTML += '<tr><td>' + o.Sr_no +
'</td><td>' + o.name +
'</td><td>' + o.employee_id +
'</td><td>' + o.last_activity +
'</td><td>' + o.total_days +
'</td></tr>';
});
$('.search_record tbody').append(trHTML);
}
}
});
}
});
Controller
public function report_attendance()
{
$employee_id=trim($this->input->post('employee_Name'));
$fromDate=trim(date('Y-m-d', strtotime($this->input->post('fromDate'))));
$toDate=trim(date('Y-m-d', strtotime($this->input->post('toDate'))));
if((!empty($employee_id)) && (!empty($fromDate)) && (!empty($toDate))){
$result=$this->Reports_model->get_employee_attendance($employee_id,$fromDate,$toDate);
}
if (empty($result) || $result == 0){
$arr_result['status'] = "error";
$arr_result['msg'] = "No record found";
}
else
{
$n=1;
foreach ($result as $row)
{
$result[] = array(
"Sr_no" => $n,
"name" => $row->firstname.' '.$row->lastname,
"employee_id" => $row->employee_id,
"last_activity"=>$row->login_time,
"total_days"=>$row->total_days
);
$n++;
}
$arr_result['status'] = 'success';
$arr_result['records'] = $result;
}
echo json_encode($arr_result);
exit;
}
view
<div class="search_record">
<table cellspacing="0" id="attendence_report_list">
<thead>
<tr>
<th class="" width="5%">Sr. No.</th>
<th class="" width="11%">Name</th>
<th class="" width="11%">Emp Id</th>
<th class="" width="9%">Date </th>
<th class="" width="9%">Working hours</th>
<th class="" width="9%">Leave Days</th>
</tr>
</thead>
<tbody>
<tr>
<tr>
</tr>
</tbody>
</table>
</div>
Change the name of the array in foreach from $result[] to results[] and check it.
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.