Display data in table on ajax success [duplicate] - php

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);

Related

Getting twice output in JSON

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.

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

Delete form data not working

My function jQuery include on my head html
$(function() {
$(".deletePage").click(function() {
var pageId = $(this).attr("id");
$.ajax({
type: "post",
url: "delete_page.php",
cache: false,
data:'id=' + pageId,
success: function(response){
try{
if(response=='true'){
parent.slideUp('slow', function() {$(this).remove();});
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
}
And my html with listPage
<table class="table table-hover">
<thead>
<tr>
<td><strong>title page</strong></td>
<td><strong>URL</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
</thead>
<tbody>
<?php
while($row_Q = mysql_fetch_array($sql_Q)){
?>
<tr>
<td><?php echo $row_Q["title"]; ?></td>
<td><?php echo $row_Q["permalink"]; ?></td>
<td>
</td>
<td>
<button type="button" class="btn btn-danger">
<a class="deletePage" href="#">Delete</a>
</button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
Why not working jQuery and not delete selected page?Any help me please?I want that click on the button "DELETE" the row its delete without going other page
thank you
You have an error. You're trying to get the page ID, but it doesn't exist in your HTML code.
Add the ID to your <a> and you're set.
I fix the problem :)
You said to me that add the Id to me and yes this is a one problem but I have more problems.
This is my new function in jQuery
$(function() {
$(".deletePage").click(function() {
var pageId = $(this).attr("id");
var parent = $(this).parent();
if(confirm("Delete me?")){
$.ajax({
type: "post",
url: "delete_page.php",
cache: false,
data: 'id=' + pageId,
dataType: "text",
success: function(response){
location.reload();
try{
if(response=='true'){
parent.slideUp('slow', function() {$(this).remove();});
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
return false;
});
});

Changing specific html table row by jquery.ajax

I have an HTML table generated by PHP querying from MySQL table.
<table>
<tr>
<th>Sl</th>
<th>ID</th>
<th>Article Name</th>
<th>Publish Status</th>
</tr>
<?php
$i = 1;
foreach ($obj->showAllFromTable('pattern') as $pattern) {
extract($pattern);
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $id; ?></td>
<td><?php echo $pattern_name; ?></td>
<td id="publish_<?php echo $id; ?>" class="status_pattern">
<?php echo $publish; ?>
</td>
</tr>
<?php
}
?>
</table>
I want to change the status of any article by clicking on the 'publish' cell of the corresponding article row. I am trying to use ajax method of jquery for this purpose as shown in the following:
<script type="text/javascript">
$(document).ready(function(){
$('.status_pattern').click(function(){
var thisid = $(this).attr('id');
$.ajax({
url: "status_change_pattern.php",
data: {
id: thisid
},
success: function (response) {
alert(response);
}
});
});
});
</script>
In the "success" block, instead of "alert", I want to create a functionality to change the text of the specific cell which I clicked. The "status_change_pattern.php" has just a text "Hey Hey".
Can anyone help? Please.
Thanks.
You have to use closure to preserve the id.
<script type="text/javascript">
$(document).ready(function(){
$('.status_pattern').click(function(){
var thisid = $(this).attr('id');
$.ajax({
url: "status_change_pattern.php",
data: {
id: thisid
},
success: function (id) {
return function (response) {
$("#" + id).html(response);
}
}(thisid)
});
});
});
</script>
You need to write,
success: function (response) {
$(thisid).html(response);
}
Here in response, you need to get new status.
The solution provided by SajithNair works. Thanks to SajithNair. But it can also be done without using closure. As shown below:
$('.status_pattern').click(function() {
var thisid = $(this).attr('id');
$.ajax({
url : "status_change_pattern.php",
data : {
id : thisid
},
success : function(response) {
$('#' + thisid).html(response);
}
});
});
Thanks

how to delete records from database with an Ajax

I am using php,mysql and ajax to delete record from a table. The problem is that the in MySQL_query it not getting the id it shows "id= undefined", i tried to pass the id to the query but i don't know where i went wrong i tried to print MySQL its shows
delete from 9xx WHERE id = undefinedArray
(
[rowid] => undefined
[supplier] => 9xx
)
can anyone tell me how to pass the id ...thanks
My ajax
$(".deletesuppliernetwork").live('click',function()
{
arr = $(this).attr('class').split( " " );
var supplier=document.getElementById("supplier").value;
if(confirm("Sure you want to delete this update?"))
{
$.ajax({
type: "POST",
url: "suppliernetwork/delete.php",
data: "rowid="+arr[2]+"&supplier="+supplier,
success: function(data){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}});
}
});
My html
<?php
include"db.php";
$supplier_id=$_GET['supplier_id'];
if($supplier_id!=""){
$sql=mysql_query("select * from $supplier_id order by country,networkname" );
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo ' <td style="width:123px" class="edit supplier '.$rows["id"].'">'.$rows["supplier"].'</td>
<td style="width:104px" class="edit rn '.$rows["id"].'">'.$rows["rn"].'</td>
<td style="width:103px" class="edit sc '.$rows["id"].'">'.$rows["sc"].'</td>
<td style="width:108px" class="edit comment '.$rows["id"].'">'.$rows["comment"].'</td>
<td style="width:62px" class="deletesuppliernetwork '.$rows["id"].'"><img src="/image/delete.png" style="margin:0 0 0 17px" ></td>
</tr>';
}
}
?>
delete.php
<?php
include"db.php";
$supplier=$_POST['supplier'];
$rownum=$_POST['rowid'];
$sql="delete from $supplier WHERE id = ".$rownum."";
print $sql;
mysql_query($sql);
print_r($_POST);
?>
<td style="width:62px" class="deletesuppliernetwork '.$rows["id"].'"><img src="/image/delete.png" style="margin:0 0 0 17px" ></td>
the index of your ID is 1, that is second index. not 2.
$.ajax({
type: "POST",
url: "suppliernetwork/delete.php",
data: "rowid="+arr[1]+"&supplier="+supplier,
success: function(data){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}});
var rowObj = $(this);
$.ajax({
type: "POST",
url: "suppliernetwork/delete.php",
data: "rowid="+arr[1]+"&supplier="+supplier,
success: function(data){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
$(rowObj).parents("tr:first").hide();
}});
this should hide your complete row.

Categories