Search option in jQuery datatables - php

I'm using jQuery data table in my site. I have integrated the "Multi-tab" functionality and "Ajax Content loading" functionality with the datatables. Now I want to integrate the search option in my data table. My coding is:
$(document).ready(function() {
$("#tabs").tabs({ // My datatable Div Id
"show": function(event, ui) {
var oTable = $('div.dataTables_scrollBody>table.display', ui.panel).dataTable();
if ( oTable.length > 0 ) {
oTable.fnAdjustColumnSizing();
}
}
});
$('#example1').dataTable({ //example1->My first table Id
"bProcessing": true,
"sAjaxSource": "test_data.php", // "test_data.php" provides content for my first table
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
$('#example2').dataTable({ // example2->My second table Id
"bProcessing": true,
"sAjaxSource": "test_data2.php", // "test_data2.php" provides content for my second table
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
I found in the "Examples of Data table" for the solution of searching option. That coding is:
var asInitVals = new Array();
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"oLanguage": {
"sSearch": "Search all columns:"
}
});
$("tfoot input").keyup( function () {
/* Filter on the column (the index) of this element */
oTable.fnFilter( this.value, $("tfoot input").index(this) );
});
/*
* Support functions to provide a little bit of 'user friendlyness' to the textboxes in
* the footer
*/
$("tfoot input").each( function (i) {
asInitVals[i] = this.value;
});
$("tfoot input").focus( function () {
if ( this.className == "search_init" )
{
this.className = "";
this.value = "";
}
});
$("tfoot input").blur( function (i) {
if ( this.value == "" )
{
this.className = "search_init";
this.value = asInitVals[$("tfoot input").index(this)];
}
});
});
Please guide me to integrate the above solution in my code otherwise please give your suggestion to integrate the search option.

This Example Code may helps you...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Working on Datatable</title>
<!-- Your JQuery Library -->
<script type="text/javascript" language="javascript" src="jquery-1.6.1.min.js"></script>
<!-- Your DataTable library -->
<script type="text/javascript" language="javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$('#userlist').dataTable({
"sDom": '<"toolbar">frtip'
});
} );
</script>
</head>
<body>
<div class="box">
<div style="width:100%;">
<table cellpadding="0" cellspacing="0" id="userlist" width="100%" style="border: 1px solid #0000CC; margin-top:10px;margin-bottom:10px;">
<thead>
<tr style=" background-color:#004677; font-size:14px; color:#fff; font-weight:bold;" height="30">
<th>Slno</th>
<th>User ID</th>
<th>Name</th>
<th>Email</th>
<th>City</th>
<th>Contact Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0001</td>
<td>Hearaman</td>
<td>hearaman.dev#gmail.com</td>
<td>Bangalore,India</td>
<td>9740798429</td>
</tr>
<tr>
<td>2</td>
<td>0002</td>
<td>Raman</td>
<td>raman#gmail.com</td>
<td>Hyderabad,India</td>
<td>886798429</td>
</tr>
<tr>
<td>3</td>
<td>0003</td>
<td>Satish Chandra</td>
<td>satishchandra.surampudi#gmail.com</td>
<td>Bangalore,India</td>
<td>948209876</td>
</tr>
<tr>
<td>4</td>
<td>0004</td>
<td>satish</td>
<td>satish#gmail.com</td>
<td>Bangalore,India</td>
<td>987639029</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
To Download DataTable plug-in and to see more examples, Visit http://datatables.net/

Ok as far as i get it. Add filter option searching i.e.
$(document).ready(function() {
$('#example1').dataTable({ //example1->My first table Id
"bProcessing": true,
"searching" : true,
"sAjaxSource": "test_data.php", // "test_data.php" provides content for my first table
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
$('#example2').dataTable({ // example2->My second table Id
"bProcessing": true,
"searching": true,
"sAjaxSource": "test_data2.php", // "test_data2.php" provides content for my second table
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});

Related

Including an editing button in a Datatable

I've been trying to do this for several days, but hope someone could just have a better idea than me, I'm trying include an edit button to my Datatable but since I'm calling the data using the method in my Controller, I am not able to find a way to make this button work
Here is my Datatable method:
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.jqueryui.min.css" rel="stylesheet" type="text/css">
<link href="https://cdn.datatables.net/scroller/2.0.2/css/scroller.jqueryui.min.css" rel="stylesheet" type="text/css">
<link href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.dataTables.min.css" rel="stylesheet" type="text/css">
<script src="//code.jquery.com/jquery-1.12.3.js"></script>
<script
src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet"
href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<script src="/js/jquery.min.js" ></script>
<script src="/js/jquery-ui.js" ></script>
<script src="https:////cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/scroller/2.0.2/js/dataTables.scroller.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
<style type="text/css">
.loader {
position:fixed;
opacity: 0.5;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('/images/double_ring.gif') 50% 50% no-repeat rgb(249, 249, 249, 249);
}
.table tr:hover { background-color: #eeeeee;}
.content { background-color:white; }
</style>
<div id="loader" class="loader" style="display:none;"></div>
<h3 id='dashboard_title_header'>Pending Proposals</h3>
<br/>
</br>
<table id="table_roster" class="display nowrap">
<thead>
<tr>
<th>Proposal Number</th>
<th>Proposal Type</th>
<th>Sponsor Code</th>
<th>Prime Sponsor Code</th>
<th>Sponsor Assigned Proposal Number</th>
<th>Department Code</th>
<th>Status</th>
<th>Submission Deadline Date</th>
<th>Project Start Date</th>
<th>Proposal Specialist</th>
<th>PI</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function format ( d ) {
return '<table id="table_child" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>IRG:</td>'+
'<td>'+d[11]+'</td>'+
'<td>IRG Date:</td>'+
'<td>'+d[12]+'</td>'+
'<td>Council Cycle:</td>'+
'<td>'+d[13]+'</td>'+
'<td>Score:</td>'+
'<td>'+d[14]+'</td>'+
'<td>Percentile:</td>'+
'<td>'+d[15]+'</td>'+
'<td>Assessment:</td>'+
'<td>'+d[16]+'</td>'+
'<td>'+
'<button class="edit-model btn btn-info">'+
'<span class="glyphicon glyphicon-edit"></span>'+
'Edit'+
'</button>'+
'</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table = $('#table_roster').DataTable({
"processing": true,
ajax: "/getproposals",
//paging: true,
//pageLenght: '10',
deferRender: true,
scrollX: true,
scrollY: 400,
scrollCollapse: true,
scroller: true,
dom: 'Bfrtip',
"columnDefs": [
{
className: "dt-body-center",
targets: -1,
defaultContent: ["<i class='glyphicon glyphicon-edit text-info editButton' aria-hidden='true'></i>"]
}
]
});
$('#table_roster tbody').on('click', 'tr', function () {
var datas = table.row( this ).data();
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
//EditProposal(data[0]);
});
$(document).on('click', '.edit-model', function() {
$('#footer_action_button').text(" Update");
$('#footer_action_button').addClass('glyphicon-check');
$('#footer_action_button').removeClass('glyphicon-trash');
$('.actionBtn').addClass('btn-success');
$('.actionBtn').removeClass('btn-danger');
$('.actionBtn').removeClass('delete');
$('.actionBtn').addClass('edit');
$('.modal-title').text('Edit');
$('.deleteContent').hide();
$('.form-horizontal').show();
var stuff = $(this).data('info').split(',');
fillmodalData(stuff)
$('#myModal').modal('show');
});
});
function EditProposal(id) {
window.open("/proposals/" + id);
}
</script>
And this is my method in the Controller
public function getProposals()
{
$sql = "SELECT proposal_number, proposal_type, sponsor_code, prime_sponsor_code, sponsor_assigned_proposal_number, award_admin_dept_code, status, submission_deadline_date, project_start_date, proposal_specialist, lname, IRG, IRGDate, CouncilCycleNumber, ScoreNumber, PercentageNumber, AssessmentEntry FROM proposal LEFT JOIN pendingproposals USING(proposal_id) LEFT JOIN proposal_research_team USING(proposal_id) WHERE proposal.status in ('Unsubmitted','Dept Approval In Process', 'Admin Office In Process', 'JIT Request Received', 'JIT Submitted', 'Submitted to Sponsor', 'Sub 1/4: Awaiting Agreement', 'Sub 2/4: Under Negotiation', 'Sub 3/4: Partially Executed') AND role = 'Lead Principal Investigator';";
$results = \DB::connection('mysql2')->select( \DB::raw($sql) );
$data = array();
$i = 0;
foreach ($results as $r) {
$data[$i] = array($r->proposal_number, $r->proposal_type, $r->sponsor_code, $r->prime_sponsor_code, $r->sponsor_assigned_proposal_number, $r->award_admin_dept_code, $r->status, $r->submission_deadline_date, $r->project_start_date, $r->proposal_specialist, $r->lname, $r->IRG, $r->IRGDate, $r->CouncilCycleNumber, $r->ScoreNumber, $r->PercentageNumber, $r->AssessmentEntry);
$i++;
}
$results2 = ["sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data];
return json_encode($results2);
}
I appreciate your help :)

Properly updates in database not in datatables server side

When we update the records in database its updated perfectly and not reflected in datatables. When we refresh the page datatables are updated.I need with out refresh the page datatables are updated.please help me.
<?php
define('DB_SERVER', 'localhost'); // Your Database host
define('DB_USERNAME', 'root'); // Your Database user name
define('DB_PASSWORD', 'root'); // Your Database password
define('DB_DATABASE', 'qwer'); // Your Database Name
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); // Connection
$sql = "SELECT nickname, email ,created_date_time,real_chips FROM users ";
$rs = mysqli_query($connection,$sql);
$str ="";
$data = array();
while ($row = mysqli_fetch_assoc($rs))
{
$str .= '<tr id="dialog-confirm">';
$str .= '<td>'.$row["nickname"].' </td> <td>'. $row["email"].'</td><td>'. $row["created_date_time"].'</td><td>'. $row["real_chips"].'</td>';
$str .= '</tr>';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Admin demo</title>
<style type="text/css" title="currentStyle">
#import "demo_page.css";
#import "demo_table.css";
</style>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<!--<link rel="stylesheet" type="text/css" href="/css/result-light.css"> -->
<script type='text/javascript' src="http://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css">
<script type='text/javascript' src="http://jquery-datatables-column-filter.googlecode.com/svn/trunk/media/js/jquery.dataTables.columnFilter.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.0.js"></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function () {
$.datepicker.regional[""].dateFormat = 'yy-mm-dd';
$.datepicker.setDefaults($.datepicker.regional['']);
drawDataTable = function()
{
$('#example').dataTable({
"aoColumns": [{
"sWidth": "200px"
},
null,
null,
null]
})
.columnFilter({
sPlaceHolder: "head:before",
aoColumns: [{
type: "text"
}, {
type: "text"
}, {
type: "date-range"
},{
type: "text"
}]
});
}
// call datatable for the first time when page loads
drawDataTable();
$('#example').on("click", "tr#dialog-confirm", function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
//' + $.trim(tableData[0]) + '
var dynamicDialog = $('<div id="MyDialog" > <div><div style="width:150px;float:left;">Amount</div><div style="float:left;">:</div><div style="width:150px;float:left;"><input type="text" name="amount" id="amount" style="width:150px;"/><input type="text" name="nickname" id="nickname" value="'+$.trim(tableData[0])+'" style="display:none;"/></div></div><div><div style="width:150px;float:left;">Password</div><div style="float:left;">:</div><div style="width:150px;float:left;"><input type="password" name="password" id="password" style="width:150px;"/></div></div></div>');
dynamicDialog.dialog({
title: "Admin chips adding",
modal: true,
height: 250,
width: 400,
buttons: [{
text: "Yes",
click: function ()
{
$.ajax({
type: "POST",
dataType: "html",
url: "Chips_AddedByAdmin.php",
cache: false,
data: {
username: $.trim(tableData[0]),
amount: $('#amount').val(),
password: $('#password').val()
},
beforeSend: function () {
$('#MyDialog').html('loading please wait...');
},
success: function (htmldata) {
//destroy existing datatable
$('#example').dataTable().fnDestroy();
//call datatable
drawDataTable();
$('#MyDialog').html("You have successfully updated the database");
dynamicDialog.dialog("close");
}
});
}
}, {
text: "No",
click: function (e) {
$(this).dialog("close");
}
}]
});
});
});
});//]]>
</script>
</head>
<body>
<table id="example" class="display">
<thead>
<tr>
<th style="width: 150px;">UserName</th>
<th style="width: 150px;">Email</th>
<th style="width: 180px;">Created Date</th>
<th style="width: 180px;">Real Chips</th>
</tr>
<tr>
<th style="width: 150px;">UserName</th>
<th style="width: 150px;">Email</th>
<th style="width: 180px;">Created Date</th>
<th style="width: 180px;">Real Chips</th>
</tr>
</thead>
<tbody>
<?php
echo $str;
?>
</tbody>
</table>
</body>
</html>
And this ajaxphp code
<?php
require_once("configure.php");
echo $nickname = $_POST['username'];
echo $amount = $_POST['amount'];
echo $password = $_POST['password'];
echo $sql = "SELECT * FROM users WHERE nickname ='admin' and password='$password';";
$rs = mysqli_query($connection,$sql);
$numrows=mysqli_num_rows($rs);
if($numrows > 0)
{
echo $sql = "update users set real_chips=real_chips+'$amount' where nickname='$nickname';";
$rs = mysqli_query($connection,$sql);
}
?>
Please could you name your files ?
What did you receive after calling the Chips_AddedByAdmin.php (if it's the second file) ?
May be you can re-run your research in order to repopulate your datatable.
Or you can do another ajax request in case of success of your first request to reload just the datatable
Best regards,
Morony

Not Update datatables properly but in database updated

When we update the records in database its updated perfectly and not reflected in datatables. When we refresh the page datatables are updated.I need with out refresh the page datatables are updated.please help me.
<?php
define('DB_SERVER', 'localhost'); // Your Database host
define('DB_USERNAME', 'root'); // Your Database user name
define('DB_PASSWORD', 'root'); // Your Database password
define('DB_DATABASE', 'qwer'); // Your Database Name
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); // Connection
$sql = "SELECT nickname, email ,created_date_time,real_chips FROM users ";
$rs = mysqli_query($connection,$sql);
$str ="";
$data = array();
while ($row = mysqli_fetch_assoc($rs))
{
$str .= '<tr id="dialog-confirm">';
$str .= '<td>'.$row["nickname"].' </td> <td>'. $row["email"].'</td><td>'. $row["created_date_time"].'</td><td>'. $row["real_chips"].'</td>';
$str .= '</tr>';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Admin demo</title>
<style type="text/css" title="currentStyle">
#import "demo_page.css";
#import "demo_table.css";
</style>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<!--<link rel="stylesheet" type="text/css" href="/css/result-light.css"> -->
<script type='text/javascript' src="http://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css">
<script type='text/javascript' src="http://jquery-datatables-column-filter.googlecode.com/svn/trunk/media/js/jquery.dataTables.columnFilter.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.0.js"></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function () {
$.datepicker.regional[""].dateFormat = 'yy-mm-dd';
$.datepicker.setDefaults($.datepicker.regional['']);
drawDataTable = function()
{
$('#example').dataTable({
"aoColumns": [{
"sWidth": "200px"
},
null,
null,
null]
})
.columnFilter({
sPlaceHolder: "head:before",
aoColumns: [{
type: "text"
}, {
type: "text"
}, {
type: "date-range"
},{
type: "text"
}]
});
}
// call datatable for the first time when page loads
drawDataTable();
$('#example').on("click", "tr#dialog-confirm", function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
//' + $.trim(tableData[0]) + '
var dynamicDialog = $('<div id="MyDialog" > <div><div style="width:150px;float:left;">Amount</div><div style="float:left;">:</div><div style="width:150px;float:left;"><input type="text" name="amount" id="amount" style="width:150px;"/><input type="text" name="nickname" id="nickname" value="'+$.trim(tableData[0])+'" style="display:none;"/></div></div><div><div style="width:150px;float:left;">Password</div><div style="float:left;">:</div><div style="width:150px;float:left;"><input type="password" name="password" id="password" style="width:150px;"/></div></div></div>');
dynamicDialog.dialog({
title: "Admin chips adding",
modal: true,
height: 250,
width: 400,
buttons: [{
text: "Yes",
click: function ()
{
$.ajax({
type: "POST",
dataType: "html",
url: "Chips_AddedByAdmin.php",
cache: false,
data: {
username: $.trim(tableData[0]),
amount: $('#amount').val(),
password: $('#password').val()
},
beforeSend: function () {
$('#MyDialog').html('loading please wait...');
},
success: function (htmldata) {
//destroy existing datatable
$('#example').dataTable().fnDestroy();
//call datatable
drawDataTable();
$('#MyDialog').html("You have successfully updated the database");
dynamicDialog.dialog("close");
}
});
}
}, {
text: "No",
click: function (e) {
$(this).dialog("close");
}
}]
});
});
});
});//]]>
</script>
</head>
<body>
<table id="example" class="display">
<thead>
<tr>
<th style="width: 150px;">UserName</th>
<th style="width: 150px;">Email</th>
<th style="width: 180px;">Created Date</th>
<th style="width: 180px;">Real Chips</th>
</tr>
<tr>
<th style="width: 150px;">UserName</th>
<th style="width: 150px;">Email</th>
<th style="width: 180px;">Created Date</th>
<th style="width: 180px;">Real Chips</th>
</tr>
</thead>
<tbody>
<?php
echo $str;
?>
</tbody>
</table>
</body>
</html>
And ajax dataupdate php is here
<?php
require_once("configure.php");
echo $nickname = $_POST['username'];
echo $amount = $_POST['amount'];
echo $password = $_POST['password'];
echo $sql = "SELECT * FROM users WHERE nickname ='admin' and password='$password';";
$rs = mysqli_query($connection,$sql);
$numrows=mysqli_num_rows($rs);
if($numrows > 0)
{
echo $sql = "update users set real_chips=real_chips+'$amount' where nickname='$nickname';";
$rs = mysqli_query($connection,$sql);
}
?>
Not sure what you have going on here, but this is completely different than how I would do it.
Lets say I had a datatable defined like this:
oTable = $("table").dataTable({ ... settings ... });
If I ever wanted to refresh that datatable, all I would ever have to call is:
oTable.fnDraw();
That's it.
Destroying, building extra functions, etc. is not needed like in your code. It's all right there for you when you open the doc's up.

Dynamically get column names in $aColumns arrary in datatables

First I'll mention what I am trying to achieve. I am using CodeIgniter framework of PHP. I have 5 tables in my database and I want to display them in Datatables format on a button click on the display page. I am using server side processing php as data source. So at first I made the code for displaying only one table in Datatable format and was successful in it. Now I want to display one table at a time out of 5 on button click event. But $aColumns length should be equal to number of columns defined in HTML table. Now considering marks tabe, it has 4 columns student_id, exam_id, subject_id and marks_achieved. Now another table is branch and has 2 columns only branch_id and branch_name. So I cannot increase or decrease tags in HTML dynamically so I am confused.
Also I am using this source to create datatables.
You can check my getTable() function here.
jQuery:
$(document).ready(function()
{
$('#datatable').dataTable({
"sPaginationType":"full_numbers",
"bJQueryUI":true,
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"sAjaxSource": "datatable/getTable",
"iDisplayStart": 0,
"iDisplayLength": 10,
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaSorting": [[0, 'asc']],
"aoColumns": [
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true }
]
})
$('input[type=button]').bind('click', function(){
var param = $(this).attr('id');
data = param + '=1';
$.ajax({
type: 'POST',
url: 'datatable',
data: data
}).done(function( data ) {
console.log(data);
$('#display_area').html(data);
});
})
});
HTML:
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/javascript.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.min.js"></script>
</head>
<body id="dt_example">
<form action="" method="post">
<input type="button" id="display_branch" name="display_branch" value="Display Branch Table" >
<input type="button" id="display_marks" name="display_marks" value="Display Marks Table" >
</form>
<div id="container">
<div id="demo">
<table id="datatable" cellpadding="0" cellspacing="0" border="0" width="100%">
<thead>
<tr>
<th>Student ID</th>
<th>Exam ID</th>
<th>Subject ID</th>
<th>Marks Achieved</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class="spacer"></div>
</div>
</body>
</html>
To get the columns dynamically I have made this change as shown below in datatable.php but it is not working. What is wrong here or I should try some other approach ?
if(isset($_POST['display_marks']))
{
$aColumns = array('student_id', 'exam_id', 'subject_id', 'marks_achieved');
$sTable = 'marks';
}
if(isset($_POST['display_branch']))
{
$aColumns = array('branch_id', 'branch_name');
$sTable = 'branch';
}
EDIT:
The solution posted by user1190992 works but the whole approach is changed. And in that I want to sanitize the headers of the columns. "branch_id" is displayed instead I want to display Branch ID. How can I perform this sanitization ?
This is a very simple way for creating HTML from JSON data dynamically. It doesn't use server side processing though.
JavaScript
$(document).ready(function() {
$(".abutton").click(function() {
$('#myDatatable_wrapper').detach(); //Remove existing table
var table = '<table id="myDatatable" class="table"><thead><tr>';
$.ajax({
url: 'dt.php',
data: "table_id="+$(this).attr("id"),
type: "POST",
success: function (data) {
$.each(data.aoColumns, function(key, value) {
table += "<th>"+value+"</th>";
});
table += "</tr></thead><tbody>";
$.each(data.aaData, function(key, row) {
table += "<tr>";
$.each(row, function(key, fieldValue) {
table += "<td>"+fieldValue+"</td>";
});
table += "</tr>";
});
table += '<tbody></table>';
$('.container').html(table);
$('#myDatatable').dataTable();
},
dataType: "json"
});
});
});
PHP
$table_id = filter_input(INPUT_POST, "table_id", FILTER_SANITIZE_STRING);
$dbconn = mysqli_connect("localhost", "username", "password");
if($table_id == "table1") {
$sql_query = mysqli_query($dbconn, 'SELECT * FROM display_branch');
}
else {
$sql_query = mysqli_query($dbconn, 'SELECT * FROM display_marks');
}
if(mysqli_num_rows($sql_query) == 0) {
echo "Check your ID";
exit(1);
}
$data = array();
$data['aaData'] = array();
while($row = mysqli_fetch_assoc($sql_query)) {
$data['aaData'][] = $row;
}
$data['aoColumns'] = array();
while($finfo = mysqli_fetch_field($sql_query)) {
$data['aoColumns'][] = $finfo->name;
}
echo json_encode($data);
HTML
<button id="table1" class="abutton">Table 1</button><br /><button id="table2" class="abutton">Table 2</button>
<div class="container"></div>
Hope this helps.

DataTables: #example working but #datatable not working when making AJAX call

I want to know the difference between #example and #datatable. I have seen one example there they are using one table with div id as datatable using some hardcoded value. And another table with div id as example . I can make a Ajax call for that second example. But i cant do it for first one.
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"bProcessing": true,
"sAjaxSource": "Json/CustomerListJson.php",
"sScrollX": "70%",
"sScrollXInner": "110%",
"bScrollCollapse": true
} );
} );
</script>
The above code is working well.
But If i change the table id to datatable like
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#datatable').dataTable( {
"bProcessing": true,
"sAjaxSource": "Json/CustomerListJson.php",
"sScrollX": "70%",
"sScrollXInner": "110%",
"bScrollCollapse": true
} );
} );
</script>
<div id="dynamic">
<table cellpadding="0" cellspacing="0" border="0" class="display dataTable" id="datatable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Email</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Country</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I got one warning pop alert which says
DataTables warning (table id = 'datatable'): Cannot reinitialise DataTable.
To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy.
This is my first project using Bootstrap CSS.
Please provide me the best way.
I want this type of look and feel.
But I got this type of table.
Finally I got this error message, if i use #datatable
DataTables warning (table id = 'datatable'): Cannot reinitialise DataTable.
To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy
You will get a warning when you initialize same datatable twice. Check this example. Using an example given in the datatable docs i was able to apply Bootstrap css. Check the same fiddle link.
If for some reason you are not able to remove the second datatable call, set bDestroy to true link this example or check this link $("#tableId").dataTable().fnDestroy();.
$('#example').dataTable({
"sScrollY": "200px",
"bPaginate": false
});
// Some time later....
$('#example').dataTable({
"bFilter": false,
"bDestroy": true //<-- set bDestroy to true which will destroy the previous initializarion
});
Change this
var oTable = $('#datatable').dataTable( {
"bProcessing": true,
"sAjaxSource": "Json/CustomerListJson.php",
"sScrollX": "70%",
"sScrollXInner": "110%",
"bScrollCollapse": true
} );
to
var oTable = $('#datatable').dataTable( {
"bProcessing": true,
"sAjaxSource": "Json/CustomerListJson.php",
"sScrollX": "70%",
"sScrollXInner": "110%",
"bScrollCollapse": true,
"bDestroy": true,
"bJQueryUI": true
} );

Categories