Iam using DataTable this is my code:
var table = $('#open').DataTable( { });
This is my html table code:
<table id="open">
<thead>
<tr>
<th rowspan="2"> S.No </th>
<th rowspan="2"> Patient Name </th>
<th colspan="2"> Booking </th>
<th rowspan="2"> Insurance Company</th>
<th rowspan="2">Appointment Status</th>
<th rowspan="2">Edit</th>
</tr>
<tr>
<th> Date </th>
<th> Time </th>
</tr>
</thead>
<tbody id="booking">
</tbody>
</table>
This is my ajax code:
var date = $("#date").val();
$.ajax({
type: 'POST',
url: 'booked1.php',
data: {
date: date
},
cache: false,
dataType: "html",
success: function (response) {
alert(response);
$("#booking").html(response);
$("#loadarModal").modal('hide');
}
});
This my booked1.php code:
if (isset($_POST['date'])) {
$date = $_POST['date'];
$query = mysqli_query($conn, "select id as id, concat(fname,' ',lname) as name, date as date, bookingtoken as bookingtoken, inusrance as insurance,
appointment_status as appointment_status from at_booking where date='$date'
");
while ($rows = mysqli_fetch_assoc($query)) {
$name = $rows['name'];
$id = $rows['id'];
$date = $rows['date'];
$bookingtoken = $rows['bookingtoken'];
$insurance = $rows['insurance'];
$appointment = $rows['appointment_status'];
echo '<tr>';
echo "<td>$id</td>";
echo "<td>$name</td>";
echo "<td>$date</td>";
echo "<td>$bookingtoken</td>";
echo "<td>$insurance</td>";
echo "<td>$appointment</td>";
echo '</tr>';
}
}
Iam successfully fetching rows through php and appending response to tbody but data table is not working properly like search is not working and no of entries not working pagination is not displaying i dont knw how to solve this can anyone help me
If you will refer dataTables doc. Then you will find that the data from remote server must be in json format. While you are not sending data in json. That is the issue. You need to change your code as below
$result = array();
while ($rows = mysqli_fetch_assoc($query)) {
$name = $rows['name'];
$id = $rows['id'];
$date = $rows['date'];
$bookingtoken = $rows['bookingtoken'];
$insurance = $rows['insurance'];
$appointment = $rows['appointment_status'];
$result[] = array($name,$id,$date,$bookingtoken,$insurance,appointment);
}
}
echo json_encode(array("data"=>$result));
EDIT
Datatable itself giving you facility for ajax. No need to explicitly add ajax for it. Remove your ajax code and change your datatable initialization to below
$('#open').DataTable( {
"ajax": 'booked1.php'
});
Also you must have same number of th and td(number of columns must be same)
you can try this --- append table using json response :
<?php
if (isset($_POST['date'])) {
$date = $_POST['date'];
$query = mysqli_query($conn, "select id as id, concat(fname,' ',lname) as name, date as date, bookingtoken as bookingtoken, inusrance as insurance,
appointment_status as appointment_status from at_booking where date='$date'
");
$data = [];
$i=0;
while ($rows = mysqli_fetch_array($query)) {
$data[$i]['name'] = $rows['name'];
$data[$i]['id'] = $rows['id'];
$i++;
}
echo json_encode($data);
}
?>
<script>
var date = $("#date").val();
$("#open tbody > tr").remove();
$.ajax({
type: 'POST',
url: 'booked1.php',
dataType : "json",
data: {
date: date
},
cache: false,
dataType: "html",
success: function (response) {
$("#loadarModal").modal('hide');
table = '';
$.each(response,function(indx,obj){
table += '<tr>';
table += '<td>'+ obj.id +'</td>';
table += '<td>'+ obj.name +'</td>';
table += '</tr>';
});
$("tbody#booking").append(table);
}
});
</script>
var table = null;
$(document).ready(function() {
table = $('#example').DataTable();
AddRowsAfterFewSeconds();
});
function AddRowsAfterFewSeconds() {
setTimeout(function() {
var strTR = '<tr>' +
'<td>YYYYY Kelly</td>' +
'<td>Senior Javascript Developer</td>' +
'<td>TTTTTT</td>' +
'<td>22</td>' +
'<td>2012/03/29</td>' +
'<td>$433,060</td>' +
'</tr>' +
'<tr>' +
'<td>SSSSS Kelly</td>' +
'<td>Senior Javascript Developer</td>' +
'<td>BBBBB</td>' +
'<td>15</td>' +
'<td>2012/03/29</td>' +
'<td>$433,060</td>' +
'</tr>';
table.rows().remove();
$(strTR).each(function() {
table.row.add($(this));
});
table.draw();
}, 3000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Roomus</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
</tbody>
</table>
This method dynamically adds rows to the DataTable. (here simply i used the setTimeOut function instead the AJAX response). It will dynamically add rows after '3 seconds'
$(strTR).each(function() {
table.row.add($(this)).draw();
});
simply loops through all the rows after converting the plain html text to 'tr' elements, and then add to the table, and finally redraws the table after adding all rows.
I've seen option to add arrays directly to DataTable. But its not working in my code. So I added them in a loop.
$(document).ready(function () {
$('#booked').DataTable();
});
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id="booked">
<thead>
<tr>
<th>Name</th>
<th>SurName</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>SurName</th>
</tr>
</tfoot>
<tbody>
<!-- Your Foreach loop starts here -->
<tr>
<td>Hello</td>
<td>How</td>
</tr>
<tr>
<td>Abc</td>
<td>XYZ</td>
</tr>
<!-- Your Foreach loop endshere -->
</tbody>
</table>
Related
I am looking to insert rows to the table but
The rows are echoed but not displayed inside the table.
The HTML code of the project is:
<div class="container">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>SN</th>
<th>Category</th>
<th>Parent</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="displayCategory">
</tbody>
</table>
</div>
The main.js file of the project is:
It fetches data from the PHP file below:
$(document).ready(function () {
manageCategory();
function manageCategory(){
$.ajax({
url: DOMAIN + "/includes/process.php",
method: "POST",
data: { manageCategory: 1 },
success: function (data) {
$("#displayCategory").html(data);
alert(data);
console.log(data);
}
})
};
}
PHP code of the project is:
<?PHP
if (isset($_POST["manageCategory"])) {
$m = new Manage();
$result = $m->manageTableWithPagination('pdcts_categories', 1);
$rows = $result['rows'];
$pagination = $result['pagination'];
if (count($rows) > 0) {
foreach ($rows as $row) {
$n = 0;
?>
<tr>
<td><?php echo ++$n; ?></td>
<td><?php echo $row["Category"]; ?></td>
<td><?php echo $row["Parent"]; ?></td>
<td>
Active
</td>
<td>
Edit
Delete
</td>
</tr>
<?php
}?>
<!-- <tr><td colspan="5"><?php echo $pagination; ?></td></tr> -->
<?php exit(); }
}?>
Try appending data (insted of html) like so:
$("#displayCategory").append(data);
note: check in the console that your php code is returning valid html (<tr> data)
EDIT: May I ask for assistance regarding this code?
This is my modal. My input text receives a value of AAA-123-0001
This script is being included into the main page via include()
<input type="hidden" class="decid" id="id" name="id">
<?php include 'includes/services_payslip_list_payslip-selection.php'; ?>
This is my services_payslip_list_payslip-selection.php
<script>
$(document).ready(function() {
$("#id").change(function() {
var id = $(this).val();
if(id != "") {
$.ajax({
url:"services_payslip_list-payslip-table.php",
data:{id:id},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#id").html(resp);
}
});
}
});
</script>
This is my services_payslip_list-payslip-table.php
<table id="example2" class="table table-bordered">
<thead>
<th>Schedule Date</th>
<th>Schedule Name</th>
<th>Recorded In</th>
<th>Recorded Out</th>
<th>Day Count</th>
<th>Day Value</th>
<th>N.D. Value</th>
<th>Leave Count</th>
<th>R.H. Count</th>
<th>R.H. Value</th>
</thead>
<tbody>
<?php
include 'includes/session.php';
if(isset($_POST['id'])) {
$id=$_POST['id']
}
$user = $user['fingerscanno'];
$sql = "SELECT fingerscanno, scheduledate, schedulename, recordin, recordout, noofdays, rate, nightdifferential, leaveday, regularholiday, specialholiday, referenceno
FROM payrollrecords WHERE fingerscanno='$user' and referenceno='$id'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr>
<td>".$row['scheduledate']."</td>
<td>".$row['schedulename']."</td>
<td>".$row['recordin']."</td>
<td>".$row['recordout']."</td>
<td>".$row['noofdays']."</td>
<td>".$row['rate']."</td>
<td>".$row['nightdifferential']."</td>
<td>".$row['leaveday']."</td>
<td>".$row['regularholiday']."</td>
<td>".$row['specialholiday']."</td>
</tr>
";
}
?>
</tbody>
</table>
What seems to be the problem here? services_payslip_list_payslip-selection.php won't load into the modal.
I need to refresh contents in table every 5 seconds. I did this with ajax and setInterval functions. But the result is not properly displayed.
This is the result displaying. Here the first row is replaced by last row. I couldn't find the reason.
Here is my code.
My controller
public function latestReport() {
$data['incomingCount'] = $this->Home_model->findCount('incoming');
$data['outgoingCount'] = $this->Home_model->findCount('outgoing');
$data['droppedCount'] = $this->Home_model->findCount('drop');
$data['latestReport'] = $this->Home_model->latestReport(10);
print_r(json_encode($data));
}
Script
function latestReport() {
$.ajax({
url : base_url + 'Home/latestReport',
type : 'POST',
success:function(data) {
var res = $.parseJSON(data);
$('#incomingCount').text(res.incomingCount);
$('#outgoingCount').text(res.outgoingCount);
$('#droppedCount').text(res.droppedCount);
var latestCount = res.latestReport.length;
for(var i = 0; i < latestCount; i++){
var count = parseInt(i) + 1;
$('#resNo').text(count);
$('#resSource').text(res.latestReport[i]['Source']);
$('#resDest').text(res.latestReport[i]['Destination']);
$('#resCallerID').text(res.latestReport[i]['CallerID']);
$('#CallerTime').text(res.latestReport[i]['CallStartTime']);
$('#resStatus').text(res.latestReport[i]['Status']);
$('#resAgent').text(res.latestReport[i]['Agent']);
$('#resType').text(res.latestReport[i]['Type']);
}
}
});
}
var myVar = setInterval(latestReport, 5000);
HTML
<table class="normal-table" id="senderidList">
<tr>
<th style="width: 100px">Sl No</th>
<th style="width: 100px">Source</th>
<th>Destination</th>
<th>CallerID</th>
<th style="width: 150px">Call Start Time</th>
<th>Status</th>
<th>Agent</th>
<th>Type</th>
</tr>
<?php if( isset($latestReport) && !empty($latestReport)) {
$i = 1;
foreach($latestReport as $report) {
?>
<tr>
<td id="resNo"><?php echo $i++;?></td>
<td id="resSource"><?php echo $report['Source']?></td>
<td id="resDest"><?php echo $report['Destination']; ?></td>
<td id="resCallerID"><?php echo $report['CallerID']?></td>
<td id="CallerTime"><?php echo date('d-m-Y h:i:s A', strtotime($report['CallStartTime'])); ?></td>
<td id="resStatus"><?php echo $report['Status']?> </td>
<td id="resAgent"><?php echo $report['Agent']?> </td>
<td id="resType"><?php echo $report['Type']?> </td>
</tr>
<?php } }
else {?>
<tr><td colspan="4"> No details available</td></tr>
<?php } ?>
</table>
I am getting the result from controller properly. But something happened when showing in table.
This is because the cells in each row all have the same ID, so you are updating the first row 10 times.
HTML elements should not have duplicate IDs.
You can do this instead, in PHP:
<tr id="row-<?php echo $i; ?>">
<td class="resNo"><?php echo $i++;?></td>
...
Then in JavaScript:
$('#row-' + count + ' .resNo').text(count);
...
Also, there is no need for parseInt(i) - just use i.
You can display your data without giving ID's to 'td' tags in HTML
make your html as follow
<table class="normal-table" id="senderidList">
<thead>
<tr>
<th style="width: 100px">Sl No</th>
<th style="width: 100px">Source</th>
<th>Destination</th>
<th>CallerID</th>
<th style="width: 150px">Call Start Time</th>
<th>Status</th>
<th>Agent</th>
<th>Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Write following code in Success of Your ajax function for appending row 1 by 1
$('#senderidList tbody').empty();//clear your data
var TableBody = '';
if (data.d.length > 0) {
//following $.each loop will Concate data one by one
$.each(data.d, function (i, latestReport) {
TableBody += '<tr><td>' + i + 1 + '<td><td>' + latestReport['Source'] + '<td><td>' + latestReport['Destination'] + '<td><td>' + latestReport['CallerID'] + '<td><td>' + latestReport['CallStartTime'] + '<td><td>' + latestReport['Status'] + '<td><td>' + latestReport['Agent'] + '<td><td>' + latestReport['Type'] + '<td></tr>';
});
}
else
{
TableBody = '<tr><td colspan="4"> No details available</td></tr>';
}
//append the created html to the table body using append function
$('#senderidList tbody').append(TableBody);
if You want to give Id to every 'td' then you can give in $.each
<td id="yourID'+i+'"> for every td in body tag
I am using DataTables where onload it shows a list of records example 10 record , After i add next record ie eleventh record(ajax) ,i brings all record after addition without refresh and append it to <tbody> part of DataTables, Now my datatable is showing 11 records. but on first page of pagination . In this condition 10 record should be present on first page of pagination and 11th on second page of pagination .But it is not working
function save_data(){
$(document).ready(function(){
var form_data = $("#myform").serialize();
$.ajax({
url:'<?php echo base_url('reclist/save');?>',
type:'post',
datatype:'json',
data: form_data,
success: function(info){
var json = JSON.parse(info);
if(json.status){
var i;
for(i=0;i < json.err_input.length;i++){
$('input[name="'+json.err_input[i]+'"]').addClass('error');
$('input[name="'+json.err_input[i]+'"]').next().addClass('error_msg');
$('input[name="'+json.err_input[i]+'"]').next().text(json.err_msg[i]);
}
}
else{
**var op = '';
$.each(json.record,function(k,v){
op+= "<tr>"+
"<td>"+v.fname+"</td>"+
"<td>"+v.lname+"</td>"+
"<td>"+v.email+"</td>"+
"</tr>";
op+= v.fname;**
});
$("#rec_list_div").html(op);
$("#result").html(json.response);
$("#result").html(json.response);
}
},
errror:function(XMLHttpRequest, textStatus, errorThrown){
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
//});
}
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tfoot>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</tfoot>
<tbody id="rec_list_div">
<?php foreach($result as $k):?>
<tr>
<td><?php echo $k->fname;?></td>
<td><?php echo $k->lname;?></td>
<td><?php echo $k->email;?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</table>
How can I retrieve this line of echo code from my php file to my jquery and I am expecting rows of values.
my php file
foreach($stmt as $warrior){
echo '<td>'.$warrior['warrior_id'].'</td><td>'.$warrior['warrior_name'].'</td><td>'.$warrior['warrior_type'].'</td>';
}
my js script
<script>
function createWarrior() {
$.post( "create_warrior.php", {
"wname": $("#txtWname").val(),
"wtype": $("#txtWtype").val()
},
function(msg){
//What should I put here
});
return false;
}
</script>
my html code
<table>
<tr>
<th colspan="3">Warrior</th>
</tr>
<tr>
<th>Warrior ID</th>
<th>Warrior Name</th>
<th>Warrior Type</th>
</tr>
<tr>
//the output should be here
</tr>
add tags <tr> at the beginning and end
foreach($stmt as $warrior){
echo '<tr><td>'.$warrior['warrior_id'].'</td><td>'.$warrior['warrior_name'].'</td><td>'.$warrior['warrior_type'].'</td></tr>';
}
the result will be
<tr><td>warrior_id_1</td><td>warrior_name_1</td><td>warrior_type_1</td></tr>
<tr><td>warrior_id_2</td><td>warrior_name_2</td><td>warrior_type_2</td></tr>
....
this answer you need to get in the js and append to html:
<script>
$.ajax({
url: 'create_warrior.php',
//Send data to php if you need. In php use $_POST['wname'] to read this data.
data: {wname: $("#txtWname").val(),wtype: $("#txtWtype").val() },
success: function(data) {
$('#dataTable').append(data);
}
});
</script>
HTML
<table id = "dataTable">
<tr>
<th colspan="3">Warrior</th>
</tr>
<tr>
<th>Warrior ID</th>
<th>Warrior Name</th>
<th>Warrior Type</th>
</tr>
</table>
Something like (note the added <tr></tr>)
foreach($stmt as $warrior){
echo '<tr><td>'.$warrior['warrior_id'].'</td><td>'.$warrior['warrior_name'].'</td><td>'.$warrior['warrior_type'].'</td></tr>';
}
with
<script>
function createWarrior() {
$.post( "create_warrior.php", {
"wname": $("#txtWname").val(),
"wtype": $("#txtWtype").val()
},
function(msg){
$('#mytable').append(msg);
});
return false;
}
</script>
and
<table id="mytable">
<tr>
<th colspan="3">Warrior</th>
</tr>
<tr>
<th>Warrior ID</th>
<th>Warrior Name</th>
<th>Warrior Type</th>
</tr>
</table>
should work I believe, didn't try it.