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>
Related
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) {
....
}
}
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 list of users in my table. At first run it will load using the data from my controller. And I have a remove button function in every row. And then in my remove button I have an ajax load AFTER the successful removal of the user. Now I load the data using ajax. But the problem is the same functionality I have at first wont work anymore. I don't know why.
Here's my code:
Initial load of user from my controller
<table class="table table-bordered table-striped table-hover" id="user-group-list">
<thead>
<tr>
<th></th>
<th>Group Name</th>
<th>Description</th>
<th class="text-center">
<span class="fa fa-plus"></span>
<button class="btn ink-reaction btn-raised btn-danger btn-sm"><span class="fa fa-trash-o"></span></button>
</th>
</tr>
</thead>
<tbody>
<?php if($user_groups) { ?>
<?php foreach($user_groups as $g) { ?>
<tr>
<td class="text-center">
<input type="checkbox" name="group_id[]" value="<?php echo $g['id']; ?>" />
</td>
<td>
<label><?php echo $g['name']; ?></label>
</td>
<td>
<label><?php echo $g['definition']; ?></label>
</td>
<td class="text-center">
<a class="btn btn-icon-toggle btn-primary edit_group" data-id="<?php echo $g['id']; ?>"><i class="fa fa-pencil"></i></a>
<?php if($g['id'] > 2) { ?>
<a class="btn btn-icon-toggle btn-danger remove_group" data-id="<?php echo $g['id']; ?>" data-name="<?php echo $g['name']; ?>"><i class="fa fa-trash-o"></i></a>
<?php } ?>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td colspan="4" class="text-center">
<p>There are no user group set</p>
</td>
</tr>
<?php } ?>
</tbody>
</table>
Then in my JS
$('.remove_group').on('click', function(e) {
e.preventDefault();
var group_id = $(this).data('id');
var name = $(this).data('name');
alert(group_id); //wont work anymore after ajax load
bootbox.dialog({
message: "Are you sure you want to remove the group <span class='text-danger'>" + name.toUpperCase() + "</span>",
title: "Notification",
buttons: {
success: {
label: "Yes, remove it",
className: "btn-info",
callback: function() {
$.ajax({
url: "<?php echo site_url('users/user/remove_user_group'); ?>",
data: {group_id: group_id},
dataType: 'json',
type: 'post',
beforeSend: function() {
console.log('Loading...');
},
success: function(d) {
loadUserGroup();
makeToast(d.status, d.toast_info);
},
error: function() {
alert('Error Found!');
}
});
}
},
danger: {
label: "Cancel",
className: "btn-default",
callback: function() {
$(this).modal('hide');
}
}
}
});
});
function loadUserGroup() {
$.ajax({
url: "<?php echo site_url('users/user/load_group_list'); ?>",
dataType: 'json',
beforeSend: function() {
var loader = "<tr>";
loader += " <td colspan='4' class='text-center'><span class='fa fa-spinner fa-pulse fa-3x'></span></td>";
loader += "</tr>";
$('#user-group-list tbody').empty();
$('#user-group-list tbody').html(loader);
},
success: function(data) {
$('#user-group-list tbody').empty();
var group_list = '';
$.each(data.user_groups, function(k, v){
group_list += "<tr>";
group_list += " <td class='text-center'><input type='checkbox' /></td>";
group_list += " <td><label>" + v.name + "</label></td>";
group_list += " <td><label>" + v.definition + "</label></td>";
group_list += " <td class='text-center'>";
group_list += " <a class='btn btn-icon-toggle btn-primary edit_group' data-id='" + v.id + "'><span class='fa fa-pencil'></span></a>";
if(v.id > 2) {
group_list += " <a class='btn btn-icon-toggle btn-danger remove_group' data-id='" + v.id + "' data-name='" + v.name + "'><span class='fa fa-trash-o'></span></a>";
}
group_list += " </td>";
group_list += "</tr>";
//console.log(v.id);
});
$('#user-group-list tbody').html(group_list);
},
error: function() {
alert('Error Occured!');
}
});
}
My ajax load
public function load_group_list() {
$json['user_groups'] = array();
$groups = $this->aauth->get_all_groups();
if(count($groups) > 0) {
foreach($groups as $group) {
$json['user_groups'][] = array(
'id' => $group['id'],
'name' => $group['name'],
'definition' => $group['definition'],
'href' => site_url('users/user/user_group_info?group_id=' . $group['id'])
);
}
}
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json");
echo json_encode($json);
}
Hope the below function fails
$('.remove_group').on('click', function(e) {//your code}
Change that to the below code
$(document).on('click','.remove_group', function(e) {//your code}
It occur because you load the class dynamically and DOM can't identify the element any more
I have data table that populates data from the database, I'm using an Ajax Call to Populate the data on the table and I'm using jQuery RowSorter.js to make my table rows draggable. The my query in my data is sorted by sortorder column. Provided that it is draggable, how can I make the sort permanent in the table and be saved on the database. The sortorder should also be updated depending on what sort order the user choose in the draggable table rows. Here's my code:
Ajax:
$.ajax({
url: "api/question/all",
type: 'GET',
success: function(result){
var myObj = $.parseJSON(result);
$.each(myObj, function(key,value) {
var t = $('#QuestionList').DataTable();
t.row.add( [
value.id,
value.columnheader,
value.costperlead,
// value.isenabled,
"<label class='toggle'><input type='checkbox' checked='' id='"+value.columnheader+"'><span class='handle'></span></label>",
value.sortorder,
"<a class='btn btn-small btn-info' href='<?php echo URL::to('question').'/';?>"+value.id+"/edit'><span class='glyphicon glyphicon glyphicon-edit' aria-hidden='true'></span></a>",
"<form method='POST' action='<?php echo URL::to('question').'/';?>"+value.id+"' accept-charset='UTF-8' class='pull-left' >"+
"<input name='_method' type='hidden' value='DELETE'>"+
"<button type='submit' class='btn btn-warning'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>"+"</form>",
] ).draw();
if(value.isenabled == "Yes")
{
$("#"+value.columnheader).prop('checked', true);
}
else if(value.isenabled == "No")
{
$("#"+value.columnheader).prop('checked', false);
}
});
}}).error(function(){
progress.progressTimer('error', {
errorText:'ERROR!',
onFinish:function(){
alert('There was an error processing your information!');
}
});
}).done(function(){
progress.progressTimer('complete');
$( "#progressbar" ).fadeOut( "slow" );
});
My Table HTML
<table id="QuestionList" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th colspan="5"> <center>Question Information<center></th>
<th colspan="2"> <center>Actions<center></th>
</tr>
<tr>
<th>ID</th>
<th>Column Header</th>
<th>Cost Per Lead</th>
<th>Is Enabled?</th>
<th>Sort Order</th>
<th>Edit/View</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7"> </td>
</tr>
</tfoot>
</table>
JS to Call rowsorter
$("#QuestionList").rowSorter({
onDrop: function(tbody, row, index, oldIndex) {
$(tbody).parent().find("tfoot > tr > td").html((oldIndex + 1) + ". row moved to " + (index + 1));
}
});
My Query
public function apiGetQuestions()
{
$questions = Question::orderBy('id', 'DESC')->get();
return json_encode($questions);
}
I'm using Laravel 5, any ideas or guides will be appreciated. Thanks!
Update:
Using Jquery's rowsorter function I can keep track of the positions of the rows and its new position:
$(tbody).parent().find("tfoot > tr > td").html((oldIndex + 1) + ". row moved to " + (index + 1));
You don't want to store the entire table, but you can store the sorting events. Everytime a user clicks on a column, you add that to a sort sequence array and save the array serialized.
var sortSequence = [];
$('th').click(function() {
// direction: 'asc' or 'desc'
sortSequence[$(this).text()] = get_direction_from_jquery_sort_plugin_somehow();
var data = {
'table': ...,
'sequence': sortSequence.serialize()
};
$.post('store-sequence', data);
});
I would then have some sanitization in place when storing the sorting to remove any duplication or ascending, descending, ascending sequences.
Then when retrieving the data, you add the sorting sequence as orderBy() calls.
$query = \DB::table("my_table")->where(...);
$sorts = $this->fetchSorting(\Auth::user(), "my_table");
foreach ($sorts as $column => $direction) {
$query->orderBy($column, $direction);
}
This is all a lot of work however and I wonder if it is really worth it.