I use Datatable in my web application.
Following is my simple code to get data using ajax.
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
<body>
<h2>AJAX SELECT</h2><hr>
<div align="center">
Select Team :
<select name="select" id ='teamSelect'>
<option value="">Select Value</option>
<option value="op2">Company 1</option>
</select>
</div>
<div id='tableContainer' align="center"></div>
<script>
$(function() {
$("#teamSelect").bind("change", function() {
$.ajax({
type: "GET",
url: "getData.php",
"dataSrc": "tableData",
success: function(html) {
$("#tableContainer").html(html);
}
});
});
});
</script>
and Getdata.php Code
<table id="mytable" class="display" cellspacing="0" width="50%">
<thead>
<tr>
<th>First name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
</tr>
</tbody>
I Link Jquery, datatable css and js both.but still It return output as normal HTML table.
No console error founded.
I need that data in datatable. So how can i get that.
and i also tested datatable in index.php page. It working quite good.
You are initializing datatable before table added. You need to initialize it in ajax
remove following script
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
update ajax as below:
<script>
$(function() {
$("#teamSelect").bind("change", function() {
$.ajax({
type: "GET",
url: "getData.php",
"dataSrc": "tableData",
success: function(html) {
$("#tableContainer").html(html);
$('#mytable').DataTable({
"destroy": true, //use for reinitialize datatable
});
}
});
});
});
</script>
Put
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
At the bottom of your Getdata.php file also links to the datatable css and js.
Or use ajaxComplete function() to call the datatable.
Related
I using Jquery to clear the table tbody and reinsert in via ajax call. after the data is showed, but the sorting function is not working properly. here is my codes..
<table class="table table-bordered table-striped table-condensed flip-content table-hover" style="table-layout:fixed;" id="datatable1">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody id="agtBody">
<?php
foreach($results as $result) :
?>
<tr>
<?php if(isset($game_name['gpname'])){?>
<td><?=$game_name['gpname']?></td>
<?php }else{ ?>
<td><?=$result['gpid']?></td>
<?php } ?>
<td style="text-align:right;"><?=Helper::money($result['betAmt'])?></td>
<td style="text-align:right;"><?=Helper::money($result['payout'])?></td>
<td style="text-align:right;"><?=Helper::money($result['winLoss'])?></td>
<td style="text-align:right;"><?=Helper::money($result['validbetamount'])?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot id ="agtFoot">
<tr style="background-color:#FFEEDD;">
<td>Total</td>
<td style="text-align:right;"><?=Helper::money($totalbetAmt)?></td>
<td style="text-align:right;"><?=Helper::money($totalpayout)?></td>
<td style="text-align:right;"><?=Helper::money($totalwinLoss)?></td>
<td style="text-align:right;"><?=Helper::money($totalvalidbetamount)?></td>
</tr>
</tfoot>
</table>
<script type="text/javascript">
function search_agtdetail(agentcode) {
if($("#agt_StartTime").val() == "" || $("#agt_EndTime").val() == "") {
alert("<?php echo 'Not Valid' ?>");
} else {
$("#agtBody").empty();
$("#agtFoot").empty();
$.ajax({
type: "post",
url: "/report/agentBoxAjax",
dataType: "json",
data: {
start_date: $("#agt_StartTime").val(),
end_date: $("#agt_EndTime").val(),
agent_code : agentcode,
},
success: function (data) {
$('#datatable1').dataTable().fnDestroy();
$('#agtBody').html(data.html);
$('#agtFoot').html(data.html_foot);
$('#datatable1').css('width', '');
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
});
}
});
}
}
$(document).ready(function(){
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
});
});
</script>
Can someone help me? The sorting is not working properly..
Its look like using the old data for sorting it.
i had less experience on jquery, someone please help. Thank you so much.
Extending on Bhushan Kawadkar comment you need to use the API method for this.Also you should be using the ajax methods for your datatable.
For example, lets say that i get the server side data from a script called data.php, i would just call it like this:
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
"ajax": {
"url": "data.php",
"type": "GET"
}
});
the post.php needs to return the data in json format like this (using car as example):
{
"data":[
[
"Ford",
"Fiesta",
"2015"
],
]
}
in your success section in the ajax call instead of destroying the table just use:
$('#datatable1').ajax.reload()
Here's a snippet just in case.
$(document).ready(function() {
var table = $('#example').DataTable({
"ajax": 'https://raw.githubusercontent.com/DataTables/DataTables/master/examples/ajax/data/arrays.txt',
});
$("#reload_table").on("click",function(){
console.log("reloading data");
table.ajax.reload();
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<html>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Profession</th>
<th>City</th>
<th>Date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</body>
<input id="reload_table" type="button" value="RELOAD TABLE">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
</html>
I created a table with my PHP and database and added a delete button on the right of each of my element in my first column and I want this button to delete the row in my database but I don't know how to link my button to a PHP action
<table border="2" class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col"><h6>Nom de l'Etape</h6></th>
<th scope="col"><h6>Description de l'Etape </h6> </th>
</tr>
</thead>
<?php
$req='SELECT * FROM Etape';
$resultat=$dbh->query($req);
while ($ligne=$resultat->fetch()) {
echo "<tr> <td>". $ligne[0]."<button type=\"button\" onclick=\"alert('Hello world!')\">delete</button></td><td>".$ligne[1]."</td> </tr>";
}
?>
</table>
The easiest way is to use ajax:
<?php
// Check if is background ajax query or user just enter page
// Is background ajax query, run PHP code
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'):
// RUN PHP CODE IN BACKGROUND (IN YOUR CASE: DELETE ROW FROM DB)
else:
// Is not ajax query - show HTML page
?>
<table border="2" class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col"><h6>Nom de l'Etape</h6></th>
<th scope="col"><h6>Description de l'Etape </h6> </th>
</tr>
</thead>
<?php
// Your PHP function to get button from database
$req='SELECT * FROM Etape';
$resultat=$dbh->query($req);
while ($ligne=$resultat->fetch()) {
echo '<tr> <td>'. $ligne[0].'<button type="button" value="<?php echo $ligne[0]; ?>">delete</button></td><td>'.$ligne[1].'</td></tr>';
}
?>
</table>
<!-- Load jQuery -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
// Button click
$(document).on('click','button',function(e) {
// Get button value
var my_id = $(this).val();
// Prepare ajax query
$.ajax({
type: "POST",
dataType:"json",
// Set url to file itself
url: window.location.href,
// set data
data: "id=" + my_id,
beforeSend: function (data) {
alert('Sending');
},
success: function (data)
{
alert('Success');
},
error: function (data)
{
alert('Error');
}
});
});
</script>
<?php endif; ?>
I have form to search any person in database.
Then I want to display the search result in DataTable.
I am using blade for templating HTML.
This is my form:
<form id="myform" method="GET" action="{{ site_url('person/search') }}">
This is my DataTable section in my HTML
<section class="panel" style="margin-top:20px;">
#include(config_item('theme').'.person.part.table-person', compact('result'), ['id' => 'persons'])
</section>
This is my table:
<table id="{{ $id }}" data-toggle="table" data-mobile-responsive="true">
<thead>
<tr>
<th data-field="image" data-align="center">Image</th>
<th data-field="id" data-visible="false">ID</th>
</tr>
</thead>
</table>
And for the last is my AJAX code:
$(document).ready(function() {
$('#myform').submit(function() {
$.ajax({
dataType: json,
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$('#persons').html(response);
}
});
return false;
});
});
With all that codes, I can't display the search result.
am I doing something wrong?
Thanks
make sure .. you cant duplicate same id name
use jQ append to display table detail
$('#channels').append(' <tr>
<th data-field="image" data-align="center">Image</th>
<th data-field="id" data-visible="false">ID</th>
</tr>');
HINT : http://api.jquery.com/append/
I am having problems trying to fetch some data from my database to display it in a value, I'm using Smarty as a template engine, I have my working code which is:
<div style="width: 50%">
<table id="listado" width="100%" cellpadding="2" cellspacing="1" border="0">
<thead>
<tr>
<th> </th>
<th style="text-align: center;">ID</th>
<th style="text-align: center;">NOMBRE</th>
<th style="text-align: center;">DOCUMENTO</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
{literal}
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
"url": API_PATH+"/empresas/",
"method": "GET",
"dataType": 'json',
'cache':false
}).done(function (response) {
var allregs = [];
$.each(response, function(key,val){
var items = [];
items.push('<tr>');
items.push('<td style="text-align: center;">seleccionar</td>');
items.push('<td style="text-align: center;">'+val.id+'</td>');
items.push('<td style="text-align: center;">'+val.nombre+'</td>');
items.push('<td style="text-align: center;">'+val.documento+'</td>');
items.push('</tr>');
allregs.push(items);
});
$('#listado tbody').append(allregs.join(''));
}).fail(function(jqXHR, textStatus){
if(jqXHR.status == 404){
alert("No existen registros");
}
});
$('body').on('click','.selectEmpresa',function(){
var empresaid = $(this).attr('data-id');
$.ajax({
"url": API_PATH+"/empresas/select/"+empresaid,
"method": "GET",
"dataType": 'json',
'cache':false
}).done(function (response) {
location.href = SERVER_PATH+'/';
}).fail(function(jqXHR, textStatus){
alert('error');
});
});
});
</script>
{/literal}
it works perfectly using normal thead, tbody, tr, td, what im trying to do is fetch the same data just val.nombre but inside :
<div class="container">
<section>
<select class="cs-select cs-skin-border">
<option value="" disabled selected>Seleccionar Empresa</option>
<option value="prueba1">Prueba 1</option>
<option value="prueba2">Prueba 2</option>
<option value="prueba3">Prueba 3</option>
</select>
</section>
</div>
<script src="{$smarty.const.ASSETS_FOLDER}/select-empresas/classie.js"></script>
<script src="{$smarty.const.ASSETS_FOLDER}/select-empresas/selectFx.js"></script>
<script>
(function() {
[].slice.call( document.querySelectorAll( 'select.cs-select' ) ).forEach( function(el) {
new SelectFx(el);
} );
})();
</script>
instead of setting the values manually I want to fetch it from the database dynamically
<a class="checkModelButton" href="addrow.php">ADD ROW</a>
<table>
<thead>
<th>Name</th>
</thead>
<tboby id="model_row">
<tr>Nokia N70</tr>
</tbody>
</table>
And jQuery:
jQuery('.checkModelButton').click(function(){
var url = jQuery(this).attr('href');
jQuery.ajax({
type:'get',
cache: false,
url: url,
success: function(html){
jQuery('#model_row').html(html);
}
});
});
in file addrow.php
<tr>Nokia N71</tr>
When I click on a tag is result is:
<table>
<thead>
<th>Name</th>
</thead>
<tboby id="model_row">
<tr>Nokia N71</tr>
</tbody>
</table>
How to fix it to result is:
<table>
<thead>
<th>Name</th>
</thead>
<tboby id="model_row">
<tr>Nokia N70</tr>
<tr>Nokia N71</tr>
</tbody>
</table>
Use .append() OR .appendTo() instead of .html()
Like
success: function(html){
jQuery('#model_row').append(html);
}
OR
success: function(html){
jQuery(html).appendTo('#model_row');
}
Using .html() will overwrite the content.
You need to append it.
$('#model_row').append(html);