Getting twice output in JSON - php

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.

Related

how to get Json and load them inside the datatable using Ajax?

I am new in AJAX and API`s:
I have created API (that returns an array of Status Items)
1- Index.php have the below code for the datatable:
<table id="example1" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th class="center">Code</th>
<th class="center">Description</th>
<th class="center">Status</th>
<th class="center">Edit</th>
<th class="center">Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot class="table-condensed table-bordered">
<tr>
<th class="center">Code</th>
<th class="center">Description</th>
<th class="center">Status</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
</table>
The second file2.php includes the Javascript and Jquery and Ajax code:
I write the code below to get the Json from the api and fetch the rows into the above table:
var table = $("#example1 tbody");
$.ajax({
url: 'API_ReadAllSeed_Status.php',
method: "GET",
xhrFields: {
withCredentials: true
},
success: function (data) {
table.empty();
$.each(data.AllStatus, function () {
var Active_Status = "";
//the code below is to set a specific element depending on the result
if (this["STATUS_ACTIVE"] == 1)
{Active_Status = "<td><span class='label label-success'>Activated</span></td>";}
else
{Active_Status = "<td><span class='label label-danger'>Deactivated</span></td>"}
table.append("<tr><td>" + this["STATUS_CODE"] + "</td><td>" + this["STATUS_DESCRIPTION"] + "</td>" + Active_Status + "</td> <td><a href='' class='btn btn-app addeditdelete' value='" + this["STATUS_ID"] + "'><i class='fa fa-edit'></i> Edit </a></td> <td><a href='' class='btn btn-app addeditdelete' value='" + this["STATUS_ID"] + "'><i class='glyphicon glyphicon-trash'> </i> Delete</a></td> </tr>");
});
}
});
Result:
The Json fetch successfully as I want but as shown in the picture, the rows are not inserted in the main body rows of the data table since nothing is working inside.
My Question:
How I am able to load the Json data into the datatable and use all its features [search and pagination and rows per page].
Finally it works nowt but still have a question:
$('#STATUS_TABLE').DataTable({
"ajax": {
"url": "API_ReadAllSeed_Status.php",
"dataSrc": "AllStatus"
},
"columns": [
{ "data": "STATUS_CODE" },
{ "data": "STATUS_DESCRIPTION" },
{ "data": "STATUS_ALT_DESCRIPTION" },
{ "data": "STATUS_ACTIVE" }
]
});
Question:
How I can change the format of the rows and to set different labels of the Status example rows with value 1 = Active and 0 = Deactivate.
After many searches and after trying many codes I found the below solution:
{ "data" : "STATUS_ACTIVE",
render : function(data, type, row) {
if (data == 1)
{data = "<span class='label label-success'>Activated</span>";}
else
{data = "<span class='label label-danger'>Deactivated</span>";}
return data;
}
},

Problems passing Ajax result to table Codeigniter

I'm trying to get table data to my view table using Codeigniter and AJAX jQuery.
Well, I'm using a document ready function to get the data instead of passing the table data when calling the view on the controller.
Ajax function
$( document ).ready(function() {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
alert("sucesso - " + data);
$('#example1').html(data);
},
error: function() {
alert('Algo falhou, nao caregou a tabela. - ' + data);
}
});
});
Controller method
public function crud_getDataAll($table_name)
{
$data = $this->Administracao_model->getAllData($table_name);
echo json_encode($data);
}
Model method
function getAllData($table_name)
{
$this->db->select('*');
$query = $this->db->get($table_name);
return $query->result();
}
View table
<table id="example1" class="table table-sm table-bordered table-striped Responsive">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Nome</th>
<th class="text-center">Ações Permissíveis</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if($data){ foreach($data as $row) { ?>
<tr>
<td class="align-middle text-center">
<?php echo $row->id;?>
</td>
<td class="align-middle text-center">
<span class="badge <?php echo $row->classes; ?>">
<?php echo $row->none;?>
</span>
</td>
<?php $ad = $row->adicionar; $el = $row->eliminar; $al = $row->alterar; $pe = $row->pesquisar; ?>
<td>
<?php echo $ad .", ". $el . ", ". $al . ", " . $pe; ?>
</td>
</tr>
<?php } } ?>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Amostra</th>
<th>Ações Permissíveis</th>
<th>Ação</th>
</tr>
</tfoot>
</table>
Is there something that I'm doing wrong? Thanks in advance.
Php error:
Severity: Notice
Message: Undefined variable: data
EDITED
output of echo json_encode($data);
[
{
"id": "1",
"nome": "Nivel 0",
"classe": "badge-admin-0",
"adicionar": "1",
"remover": "1",
"alterar": "1",
"pesquisar": "1"
},
{
"id": "2",
"nome": "Teste",
"classe": "badge-danger",
"adicionar": "1",
"remover": "0",
"alterar": "0",
"pesquisar": "0"
}
]
Basically you have 2 options here. First of all, if you're not passing $data to your HTML table, then remove PHP codes:
<table id="example1" class="table table-sm table-bordered table-striped table-responsive">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Nome</th>
<th class="text-center">Ações Permissíveis</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Amostra</th>
<th>Ações Permissíveis</th>
<th>Ação</th>
</tr>
</tfoot>
</table>
but if you're passing the data, leave as it is.
Option 1: Output data as HTML
$( document ).ready(function() {
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
processData: false,
dataType: 'html',
success: function(data) {
$('#example1 tbody').html(data);
},
error: function(xhr) {
alert('Algo falhou, nao caregou a tabela. - ' + xhr.statusText);
}
});
});
Then, in your controller, output data as HTML:
public function crud_getDataAll($table_name)
{
$rows = $this->Administracao_model->getAllData($table_name);
foreach($rows as $row) {
echo '<tr>';
echo '<td class="align-middle text-center">' . $row->id . '</td>';
echo '<td class="align-middle text-center"><span class="badge ' . $row->classe . '">' . $row->nome . '</span></td>';
echo '<td>' . $row->adicionar . ', ' . $row->eliminar . ', ' . $row->alterar . ', ' . $row->pesquisar . '</td>';
echo '</tr>';
}
}
Option 2: Output data as JSON
Just update your AJAX callback:
$( document ).ready(function() {
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
processData: false,
dataType: 'json',
success: function(rows) {
if (rows) {
rows.forEach(function(row) {
$('#example1 tbody').append(`<tr><td class="align-middle text-center">${row.id}</td><td class="align-middle text-center"><span class="badge ${row.classe}">${row.nome}</td><td>${row.adicionar}, ${row.eliminar}, ${row.alterar}, ${row.pesquisar}</td></tr>`);
});
}
},
error: function(xhr) {
alert('Algo falhou, nao caregou a tabela. - ' + xhr.statusText);
}
});
});

Data is not Loaded on bootstrap-table using php ajax

i am creating a simple crud system while i loading the data data is not loaded. but i got the data from the all_category.php successfully.i checked through console.log
0: {id: 65, catname: "sad", status: 1}
1: {id: 62, catname: "Pepsi", status: 1}
2: {id: 60, catname: "Mobile", status: 1}
what i tried tried so far i attached code below. i tried this for 2 days but couln't solve this . data is not passing to the table . i attached the screen shot image below
Form design of the table
<table id="tblCenters" data-toggle="table" data-show-refresh="true"
data-show-toggle="true" data-show-columns="true" data-search="true"
data-select-item-name="toolbar1" data-pagination="true" data-sort-name="aid"
data-sort-order="desc">
<thead>
<tr>
<th data-field="catname" data-sortable="true">Category</th>
<th data-field="status" data-sortable="true">Status</th>
<th data-field="opt" data-sortable="true">Edit</th>
</tr>
</thead>
<tr>
</tr>
</table>
Jquery
function get_all() {
$.ajax({
type: 'POST',
url: 'all_category.php',
dataType: 'json',
success: function (data) {
console.log(data);
$('#tblCenters').bootstrapTable('removeAll');
for (var i = 0; i < data.length; i++) {
var btnCell = '<button id="u' + data[i][0] + '" type="button" class="btn btn-success btn-xs" onclick="updateAcc(this)">Edit</button>';
addRow(data[i][1], data[i][2], btnCell);
}
}
,
error: function (data) {
console.log(data);
}
});
function addRow(catname,status,cell) {
$('#tblCenters').bootstrapTable('insertRow', {
index: 1,
row: {
catname: catname,
status:status,
opt:cell
}
});
}
all_category.php
<?php
include("db.php");
$stmt = $conn->prepare("select id,catname,status from category order by id DESC ");
$stmt->bind_result($id,$catname,$status);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("id"=>$id, "catname"=>$catname,"status"=>$status);
}
echo json_encode( $output );
}
$stmt->close();

Display data in table on ajax success [duplicate]

This question already has answers here:
jQuery parse JSON multidimensional array
(2 answers)
Closed 3 years ago.
I am submitting the form from ajax, and after ajax success i want to display all data in table tr td.
Below is my response which i got on ajax success and i want to load inside table on ajax success, but its displaying blank table.
{"raildata":null,"killdata":[{"id":146,"acct_id":1885,"AcctNo":"UP2357"},{"id":145,"acct_id":1885,"AcctNo":"UP2357"}]}
Below is my jquery ajax code which i tried, but its not displaying data after form submit on success.
$(document).ready(function(){
$('#killfrm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '<?= Router::url(['controller' => 'Killsheets', 'action' => 'addKillsheet']) ?>',
data: $('form').serialize(),
beforeSend: function(){
$('#ibox1').children('.ibox-content').toggleClass('sk-loading');
},
success: function(response) {
var trHTML = '';
$(response).each(function (i,value) {
trHTML += response.killdata.map(function(killdata) {
return '<tr class="gradeA"><td>' + killdata.id + '</td><td>' + killdata.AcctNo + '</td></tr>';
});
trRailHTML += response.raildata.map(function(raildata) {
return '<tr class="gradeA"><td>' + raildata.rail_no + '</td><td>' + raildata.scale_no + '</td><td><button title="View" class="btn btn-default btn btn-xs tblbtn">View</button></td></tr>';
});
});
$('#txtcount').val(sum);
$('#listRail').html(trRailHTML);
$('#listKill').html(trHTML);
},
error: function(response) {
console.log(response);
}
});
});
});
Below is my HTML table
<table class="table table-bordered">
<thead>
<tr>
<th>Sheet#</th>
<th>Acc #</th>
<th>Action</th>
</tr>
</thead>
<tbody id="listKill"> </tbody>
</table>
you can pass $.each:
script:
$(document).ready(function(){
$('#killfrm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '<?= Router::url(['controller' => 'Killsheets', 'action' => 'addKillsheet']) ?>',
data: $('form').serialize(),
beforeSend: function(){
$('#ibox1').children('.ibox-content').toggleClass('sk-loading');
},
success: function(response) {
let trHTML = '';
let killData = response.killdata;
let raildata = response.raildata;
$.each(killData, function(kill) {
let killid = kill.id;
let killacct_id = kill.acct_id;
let killAcctNo = kill.AcctNo;
trHTML += '<tr>';
trHTML += '<td>'+killid+'</td>';
trHTML += '<td>'+killacct_id+'</td>';
trHTML += '<td>'+killAcctNo+'</td>';
trHTML += '</tr>';
});
$('#listRail').html(raildata);
$('#listKill').html(trHTML);
},
error: function(response) {
console.log(response);
}
});
});
});
you get result html trHTML in id of #listKill:
html:
<table class="table table-bordered">
<thead>
<tr>
<th>Sheet#</th>
<th>Acc #</th>
<th>Action</th>
</tr>
</thead>
<tbody id="listKill">result goes here </tbody>
</table>
you can get any response data from response.objectkey = get value
for get json data in ajax response you need to pass ajax options :
dataType:"json"
go with below example:
$.ajax({
type: 'post',
url: 'Your Url',
data: $('form').serialize(),
dataType:'json',
success: function(response) {
response == here you get object you can get any value by object key
}
});
your json response:
{"raildata":null,"killdata":[{"id":146,"acct_id":1885,"AcctNo":"UP2357"},{"id":145,"acct_id":1885,"AcctNo":"UP2357"}]}
you can get result by using response variable like below
console.log(response.killdata);
console.log(response.raildata);
try above if you get any help
Table body is appended like this:
Assin id to your table
<table class="table table-bordered" id='my_table'>
Add this row to add the new rows
$("#my_table tbody").append(trHTML);

how to set class on table in spesific tr?

I need to set class on table on spesific tr on ajax proses. my html table like below
<table class="table table-striped table-borderless table-hover" id="tablePray">
<thead>
<tr>
<th style="width:20%;">Nama / Name</th>
<th style="width:45%;">Keterangan / Description</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
foreach ($prays as $row)
{
?>
<tr id="prayRow<?php echo $row->id;?> ">
<td class="user-avatar"> <img src="<?php echo base_url();?>assets/admin/img/avatar.gif" alt="Avatar"><?php echo $row->name;?></td>
<td><?php echo $row->prayNeed;?></td>
<td class="text-right"> Healed</td>
</tr>
<?php
}
?>
and my jquery like this :
$('#changeStatusFrm').submit(function(e) {
e.preventDefault();
$id=$('#idPray').val();
$token=$('#token').val();
data = new FormData();
data.append("idPray",$id);
data.append("<?php echo $this->security->get_csrf_token_name();?>", $token );
$.ajax({
data: data,
type: "POST",
url: '<?php
echo base_url('Pray/ChangeStatus');
?>'
,
cache: false,
contentType: false,
processData: false,
success: function(url) {
var result=url.split('|');
$('#token').val(result[0]);
alert('Pray status have been change');
$("#mod-danger").modal("hide");
$("#tablePray tr#prayRow"+$id).addClass('table-success');
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I want to change the spesific tr if row link get click.
Can anybody help me?? thx
If you are using datatable then you can use something like this :
$('#tablePray').dataTable( {
"columnDefs": [
{ className: "my_class", "targets": [ 0 ] }
]
} );
reference link :- https://datatables.net/reference/option/columns.className
This example here demonstrates adding and removing classes on a row from a click event.
Set like this
var val = "#prayRow"+$id;
$(val).addClass('table-success');
Make sure #prayRow$id is already defined in table
FYI: move alert('Pray status have been change'); to end of the line

Categories