i'm beginner in codeigniter. i work using cart library from codeigniter and it's work fine. but i have another values as weight and amount (interger value) in my list cart. example when i adding a same value in twice, just qty and subtotal has increased. the weight and amount just update where i Last input not calculate from old value with new value. how i can solved this..?
i'm using CI v3.1 and datatables for show the list cart,
sorry for my bad english language. best regards :)
here my controller cart
//adding to cart list
public function addbarang()
{
$data = array(
'id' => $this->input->post('id_barang'),
'price' => str_replace('.', '', $this->input->post('harga_barang')),
'qty' => $this->input->post('qty'),
'unit' => $this->input->post('j-unit'),
'name' => $this->input->post('nama_barang'),
'nama_jenis' => $this->input->post('j-nama_jenis'),
'id_jenis' => $this->input->post('j-id_jenis'),
'options' => array('j-berat' => $this->input->post('j-weight'),'j-amount' => $this->input->post('j-amount'))
);
$insert = $this->cart->insert($data);
echo json_encode(array("status" => TRUE));
//echo"<pre>";
//print_r($this->cart->contents());
// echo"<pre>";
}
//show cart list in datatables
public function ajax_list_transaksi()
{
$data = array();
$no = 1;
foreach ($this->cart->contents() as $items){
$row = array();
$row[] = $no;
$row[] = $items["id"];
$row[] = $items["name"];
$row[] = $items["id_jenis"];
$row[] = $items["nama_jenis"];
$row[] = $items["qty"];
$row[] = $items["unit"];
$row[] = $items["options"]["j-berat"];
$row[] = $items["options"]["j-amount"];
$row[] = 'Rp. ' . number_format( $items['price'],
0 , '' , '.' ) . ',-';
$row[] = 'Rp. ' . number_format( $items['subtotal'],
0 , '' , '.' ) . ',-';
//add html for action
$row[] = '<a href="javascript:void(0)" style="color:rgb(255,128,128); text-decoration:none" onclick="deletebarang('
."'".$items["rowid"]."'".','."'".$items['subtotal']."'".')"> <i class="fa fa-close"></i> Delete</a>';
$data[] = $row;
$no++;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
my js to show and adding value cart list
//the js to show cart list in html
var table;
$(document).ready(function() {
table = $('#table_transaksi').DataTable({
"paging": true,
"ordering": false,
"info": false,
"searching": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?= site_url('Master_rabp/ajax_list_transaksi')?>",
"type": "POST"
},
"columnDefs": [{
"targets": [ 0,1,2,3,4,5,6 ],
"orderable": false,
}],
});
});
function reload_table()
{
table.ajax.reload(null,false);
}
//the js for adding new cart value
function addbarang()
{
var id_barang = $('#id_barang').val();
var qty = $('#qty').val();
if (id_barang == '') {
$('#id_barang').focus();
}else if(qty == ''){
$('#qty').focus();
}else{
$.ajax({
url : "<?= site_url('Master_rabp/addbarang')?>",
type: "POST",
data: $('#form_transaksi').serialize(),
dataType: "JSON",
success: function(data)
{
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding data');
}
});
$('.reset').val('');
};
}
function deletebarang(id,sub_total)
{
// ajax delete data to database
$.ajax({
url : "<?= site_url('Master_rabp/deletebarang')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
Related
I need some help plz!!
I need to give each variable an id to use it later to make an ajax click on method action to enter the $folder subdirectory's inside the table.
Do I have to do that in the controller or in the ajax?
The data tables plugin is used in the application: https://datatables.net/
// These are the three functions: Controller function, Ajax function, and Bootstrap, as you can see the folders at the top of the table then the medias will be listed, I am not having any problem with the code and its working fine.
public function ajaxSearchMedias() {
$this->checkAccessPlaylists(false) ;
$this->loadModelSpe('Media');
$this->loadModelSpe('media');
$orderby = 'name' ;
$orderway = 'ASC' ;
$search = NULL ;
if(isset($_POST['order'][0]["column"])) {
$column_to_order = (int) $_POST['order'][0]["column"] ;
if($column_to_order == 2)
$orderby = 'length' ;
}
if(isset($_POST['order'][0]["dir"])) {
$way_to_order = $_POST['order'][0]["dir"] ;
if(strtolower($way_to_order) == 'desc')
$orderway = 'DESC' ;
}
if($_POST['search']["value"])
$search = $_POST['search']["value"] ;
$data = array();
// Display folders in the content playlists
if(isset($_POST['folderId']) && $_POST['folderId'] != -1) {
$level = $this->media->getFolderLevel($_POST['folderId'])->level;
$level++;
$parentFolder = $_POST['folderId'];
$folders = $this->media->getFoldersByParentFolderId($_POST['folderId']);
$medias = $this->media->getMediasByParentFolderId($_POST['folderId']);
}else {
$siteId = $_SESSION["sess_id_site"];
$folders = $this->media->getRootFoldersBySiteId($siteId);
$medias = $this->media->getRootMediasBySiteId($siteId);
}
if($folders) {
foreach ($folders as $folder){
//$name = $newtext = wordwrap( $one_media->name, 15, "\n", true );
$name = $folder->name;
$name = '<span>'.$name.'</span>';
$unformatted_length = Helper::getLengthForMedia(array("type" => $folder->type)) ;
$length = Helper::convertSecondsToMinutesSeconds($unformatted_length) ;
$orientation_and_type_icon = '<div class="" data-name="'.htmlspecialchars($folder->name, ENT_QUOTES, 'UTF-8').'" data-length="'.$length.'" data-unformatted_length="'.$unformatted_length.'" data-id="'.$one_media->id.'" data-type="media" >' ;
$orientation_and_type_icon .= '<span class="icon">'.Helper::getIconForTypeAndOrientationForMedia($folder).'</span>' ;
$orientation_and_type_icon .= '<span class="thumbnail" style="display:none;">'.Helper::getThumbnailForMedia($folder, $this->current_id_company, $this->current_id_site, "img-thumbnail").'</span>' ;
$orientation_and_type_icon .= '<button type="button" id="'.$folder->name.'" > <span class="glyphicon glyphicon-plus-sign"></span></span></button>' ;
$orientation_and_type_icon .= '</div>' ;
array_push($data, array('orientation_and_type_icon' => $orientation_and_type_icon, 'name' => $name, 'length' => $length));
}
}
// Display Medias in the content playlist
$medias = $this->Media->getMediasForContentPlaylists($search, $orderby, $orderway, 500, $this->current_id_site, $id_folder = NULL);
if($medias) {
foreach ($medias as $one_media){
//$name = $newtext = wordwrap( $one_media->name, 15, "\n", true );
$name = $newtext = $one_media->name;
$name = '<span>'.$name.'</span>';
$unformatted_length = Helper::getLengthForMedia(array("type" => $one_media->type, "length" => $one_media->length)) ;
$length = Helper::convertSecondsToMinutesSeconds($unformatted_length) ;
$orientation_and_type_icon = '<div class="pl_media_data" data-name="'.htmlspecialchars($one_media->name, ENT_QUOTES, 'UTF-8').'" data-length="'.$length.'" data-unformatted_length="'.$unformatted_length.'" data-id="'.$one_media->id.'" data-type="media" >' ;
$orientation_and_type_icon .= '<span class="icon">'.Helper::getIconForTypeAndOrientationForMedia($one_media).'</span>' ;
$orientation_and_type_icon .= '<span class="thumbnail" style="display:none;">'.Helper::getThumbnailForMedia($one_media, $this->current_id_company, $this->current_id_site, "img-thumbnail").'</span>' ;
$orientation_and_type_icon .= '</div>' ;
array_push($data, array('orientation_and_type_icon' => $orientation_and_type_icon, 'name' => $name, 'length' => $length));
}
}
$json_result = json_encode(array("data" => $data));
print $json_result;
}
// This is the ajax function, this function list media's and folders using data tables plugin without any problem, the main problem is giving an id to folders different than the media's so I can use it to make the click on for the folders.
this.getMediaList = function() {
var jqxhr = $.getJSON( url + 'plugins/DataTables-1.10.12/media/js/i18n/fr_FR.json', function( data ) {});
jqxhr.done(function(data) {
self.pl_dt_language_json = data ;
var languages_dt = self.pl_dt_language_json ;
languages_dt = $.extend(languages_dt, {"sSearch": ""});
self.pl_medias_dt = $('#pl_medias').DataTable({
language: languages_dt,
"columns": [
{ "data": "type" },
{ "data": "orientation_and_type_icon" },
{ "data": "name" },
{ "data": "length" },
],
"columnDefs": [
{ "searchable": false, "orderable": false, "targets": 0 },
{ className: "pl_media_cell_type", "targets": [ 0 ] } ;
{ className: "pl_media_cell_icon", "targets": [ 1 ] } ,
{ className: "pl_media_cell_name", "targets": [ 2 ] } ,
{ className: "pl_media_cell_length", "targets": [ 3 ] }
],
"order": [[ 1, 'asc' ]],
initComplete: function(settings, json) {
// search
if($('#pl_medias_filter input').eq(0).size() > 0) {
$('#pl_medias_filter input').eq(0).attr("placeholder", "Rechercher un fichier") ;
$('#pl_medias_filter input').unbind();
$('#pl_medias_filter input').on( 'keyup', function () {
var searchInput = $(this).val();
if(searchInput.length == 0) {
window.clearTimeout(self.pl_medias_dt_filter_status);
self.pl_medias_dt.search( searchInput ).draw();
} else {
if(searchInput.length < 3) {
window.clearTimeout(self.pl_medias_dt_filter_status);
self.pl_medias_dt_filter_status = setTimeout(function() {
self.pl_medias_dt.search( searchInput ).draw() ;
}, 3000);
} else {
window.clearTimeout(self.pl_medias_dt_filter_status);
self.pl_medias_dt_filter_status = setTimeout(function() {
self.pl_medias_dt.search( searchInput ).draw()
}, 1000);
}
}
});
}
},
drawCallback: function(settings) {
// refresh drag and drop
self.initDragDropSortElementForContentPlaylist();
},
"serverSide": true,
"paging": false,
"lengthChange" : false,
"scrollY": 122,
"info": false,
"ajax": {
url : url + "playlists/ajaxSearchMedias", // json datasource
type: "post"
},
"dom": '<lf<t>ip>'
});
});
},
// This is the Bootstrap script
<div class="pl_block_wrapper pl_block_media_wrapper row">
<div class="col-xs-2 pl_block_label"><span>AUTOPROMO</span></div>
<div class="col-xs-10 pl_block_container_middle">
<table id="pl_medias" class="table table-striped table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<th>Type</th>
<th>Nom</th>
<th>Durée</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
As you can see the three Bootstrap ajax jquery and PHP scripts.
I found a simple solution to add an id and a class :-) :
$('#pl_medias tr').attr('id', 'table-row-id');
$('#pl_medias tr').attr('class', 'table-row-class');
Thank you very much!
This is my DataTable code:
$('#open').DataTable( {
select: true,
"processing": true,
"sAjaxSource": "booked1.php",
"serverside": true,
"columns" :[ {
"data" : "name"
}, {
"data" : "date1"
}, {
"data" : "bookingtoken"
}, {
"data" : "insurance"
}]
} );
This is my ajax call :
$("#submit").on('click', function () {
$('#loadarModal').modal({backdrop: 'static', keyboard: false});
var date = $("#date").val();
//alert(date);
if (date == '') {
$("#dateText").show();
$("#dateText").html("Please select date");
$("#loadarModal").modal('hide');
} else {
$("#dateText").hide();
//alert("can processd");
var data = $("#form").serialize();
$.ajax({
type: 'POST',
url: 'booked1.php',
data: {
date: date
},
cache: false,
dataType: "html",
success: function (response) {
alert(response);
if(response==''){
}
$("#booking").html(response);
$("#loadarModal").modal('hide');
}
});
}
});
This is my PHP Script:
include 'd_b_con.php';
if(isset($_POST['date'])){
$date=$_POST['date'];
$query=mysqli_query($conn,"select date as date ,tokenno as tokenno ,inusrance as inusrance,bookingtoken as bookingtoken ,
fname as fname,lname as lname , status as status from at_booking where date='$date'");
$data=array();
while($row1=mysqli_fetch_array($query)){
$data[] = $row1;
$date1=$row1['date'];
$tokenno=$row1['tokenno'];
$bookingtoken=$row1['bookingtoken'];
$fname=$row1['fname'];
$lname=$row1['lname'];
$status=$row1['status'];
$insurance=$row1['inusrance'];
$name=$fname.' '.$lname;
echo '<tr>';
echo "<td>$name </td>";
echo "<td> $date1 </td>";
echo "<td>$bookingtoken </td>";
echo "<td>$insurance </td>";
echo '</tr>';
$result=array(
"name" => $name,
"date1" => $date,
"bookingtoken" => $bookingtoken,
"insurance" => $insurance
);
echo json_encode($result);
}
This is the first time I am using server side data tables.
I am getting error like "DataTables warning: table id=open - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"
Can anyone guide me how to use data tables server side for my code.
Try to change this code,
$result = [];
$result[]=array(
"name" => $name,
"date1" => $date,
"bookingtoken" => $bookingtoken,
"insurance" => $insurance
);
echo json_encode($result);
die;
Once check in network->xhr whether you are getting any response or not.
You really overcomplicate this. You should never echo out the actual <tr><td>.. markup, this is why you get the warning. And use mysqli_fetch_assoc instead :
$data = array();
while( $row1 = mysqli_fetch_assoc($query) ){
$row1['name'] = $row1['fname'].' '.$row1['lname'];
$row1['date1'] = $row1['date']; //??
$data[] = $row1;
}
echo json_encode($data);
Update. You will probably need to use
echo json_encode( array('data' => $data) );
If you not set dataSrc to ''.
I am a stuck with a problem.
I am having an ajax Datatable where I need to load the data via ajax. When I implemented the code Datatable pagination and sorting is not working. No error is displayed in the console. Don't know what to do.
here is my code...........
Controller Function
public function ajaxdata(Request $request)
{
$merchants = \DB::table('merchantsummary')->lists('id');
$queryBuilder = OrderQueueModel::take($request->input('length'))
->skip($request->input('start'))->select('order_queue.qid','order_queue.qorder_no','order_queue.created_at','customer.first_name','customer.last_name','merchant_queue_order.created_at as merchant_order_time')
->join('customer','customer.id','=','order_queue.customerid')
->join('merchant_queue_order','order_queue.qid','=','merchant_queue_order.order_queue_id')
->groupBy('merchant_queue_order.order_queue_id');
$orders = $queryBuilder->get();
$data = array();
$i=1;
foreach($orders as $order):
$merchant = MerchantOrderQueueModel::select('merchantsummary.merchant_name','merchant_queue_order.order_queue_id')
->join('merchantsummary','merchantsummary.id','=','merchant_queue_order.merchant_id')
->WHERE('merchant_queue_order.order_queue_id',$order->qid)
->get();
$merchList = '';
foreach($merchant as $mer):
if($merchList!=''){
$merchList .= ', ';
}
$merchList .= $mer->merchant_name;
endforeach;
$data[] = [ $i,
$order->qorder_no,
ucfirst($order->first_name).ucfirst($order->last_name),
date('d-m-Y H:i A', strtotime($order->created_at)),
date('d-m-Y H:i A', strtotime($order->merchant_order_time)),
$this->dateDifference($order->merchant_order_time,$order->created_at),
$merchList,
'</i> View',
];
$i++;
endforeach;
$totaldata = OrderQueueModel::count();
$totalfiltered = $orders->count();
$json_data = array(
"draw" => intval( $_REQUEST['draw'] ),
"recordsTotal" => intval( $totaldata ),
"recordsFiltered" => intval( $totalfiltered ),
"data" => $data
);
echo json_encode($json_data);
}
TableAjax.js
var orderRecords = function () {
var grid = new Datatable();
grid.init({
src: $("#order_ajax"),
onSuccess: function (grid) {
// execute some code after table records loaded
},
onError: function (grid) {
// execute some code on network or other general error
},
onDataLoad: function(grid) {
// execute some code on ajax data load
},
loadingMessage: 'Loading...',
dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options
// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/scripts/datatable.js).
// So when dropdowns used the scrollable div should be removed.
//"dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>",
"bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.
"lengthMenu": [
[5,10, 20, 50, 100],
[5,10, 20, 50, 100] // change per page values here
],
"pageLength": 5, // default record count per page
"serverSide": true,
"columnDefs":[
{ // set default column settings
'orderable': true, 'targets': [0] },
{ "searchable": true, "targets": [0] },
],
"ajax": {
"url": "order/data", // ajax source
},
"order": [
[1, "asc"]
]// set first column as a default sort by asc
}
});
// handle group actionsubmit button click
grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
e.preventDefault();
var action = $(".table-group-action-input", grid.getTableWrapper());
if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
grid.setAjaxParam("customActionType", "group_action");
grid.setAjaxParam("customActionName", action.val());
grid.setAjaxParam("id", grid.getSelectedRows());
grid.getDataTable().ajax.reload();
grid.clearAjaxParams();
} else if (action.val() == "") {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'Please select an action',
container: grid.getTableWrapper(),
place: 'prepend'
});
} else if (grid.getSelectedRowsCount() === 0) {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'No record selected',
container: grid.getTableWrapper(),
place: 'prepend'
});
}
});
}
Need Help !! Waiting for the response..
The easiest way to apply server side data-table is:
Jquery:
$(document).ready(function() {
$('#data_table').dataTable({
"sServerMethod": "POST",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "get_data.php"
});
});
Php: get_data.php
$start = $_REQUEST['iDisplayStart']; // to handle pagination
$length = $_REQUEST['iDisplayLength']; // to handle pagination
$sSearch = $_REQUEST['sSearch']; // for searching
$col = $_REQUEST['iSortCol_0'];
$arr = array(0 => 'id', 1 => 'first_name', 2 => 'last_name', 3 => 'email');
$sort_by = $arr[$col];
$sort_type = $_REQUEST['sSortDir_0'];
$qry = "select id, first_name, last_name, email, position, office from datatables_demo where (first_name LIKE '%".$sSearch."%' or last_name LIKE '%".$sSearch."%' or email LIKE '%".$sSearch."%') ORDER BY ".$sort_by." ".$sort_type." LIMIT ".$start.", ".$length;
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
$data[] = $row;
}
$qry = "select count(id) as count from datatables_demo";
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
$iTotal = $row['count'];
}
$rec = array(
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iTotal,
'aaData' => array()
);
$k=0;
if (isset($data) && is_array($data)) {
foreach ($data as $item) {
$rec['aaData'][$k] = array(
0 => $item['id'],
1 => '<span id="'.$item['id'].'" name="first_name" class="editable">'.$item['first_name'].'</span>',
2 => '<span id="'.$item['id'].'" name="last_name" class="editable">'.$item['last_name'].'</span>',
3 => '<span id="'.$item['id'].'" name="email" class="editable">'.$item['email'].'</span>',
4 => '<span id="'.$item['id'].'" name="position" class="editable">'.$item['position'].'</span>',
5 => '<span id="'.$item['id'].'" name="office" class="editable">'.$item['office'].'</span>'
);
$k++;
}
}
echo json_encode($rec);
Its a little bit tough to understand the code on first time, but it will render full functional server side data-table
I am trying to send last value (af) of this URL www.example.com/country/AF.html through AJAX data and want to read this data in Codeigniter Controller but unable to retrieve data. Please help
Datatable Ajax Code
$(document).ready(function() {
var UserURL = window.location.href.split("/").pop();
var newurl = UserURL.split("/").slice(-1).join().split(".").shift();
$('#countryiptable').DataTable({
"pageLength": 50,
"info": false,
"processing": true,
"serverSide": true,
'ajax': {
'url': "country/getlist",
"type": "POST",
"data":{"country_code": newurl},
"dataType": "json",
"dataSrc": function (jsonData){
return jsonData.data;
}
}
});
} );
and here is my Codeigniter Controller;
public function getlist(){
echo $this->input->post('country_code');
$countryiso2 = strtoupper($this->input->post('country_code'));
//echo "hi";
$list = $this->CountryModel->getCountry($countryiso2);
$data = array();
$no = $_POST['start'];
foreach ($list as $iplist) {
// print_r($data);die;
$no++;
$row = array();
$row[] = $no;
$row[] = $iplist->startip;
$row[] = $iplist->registry_name;
$row[] = $iplist->totalip;
$row[] = $iplist->country_code;
$row[] = $iplist->ip_type;
$data[] = $row;
//$_POST['draw']='';
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->CountryModel->count_all(),
"recordsFiltered" => $this->CountryModel->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
}
Is there a way to add row as html to datatable? I understand that the suggested way of doing it is this:
$('#addRow').on( 'click', function () {
t.row.add( [
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw( false );
counter++;
} );
But I have a complex JSON input and I want to pre process it in PHP. Is it doable or even possible?
EDIT:
So instead of doing the code above:
t.row.add(resultfromphpserverwithalltherows);
UPDATE:
JSON output
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
and sometimes:
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed","othersubjects":[{"applied math":"90","general science":96,"world history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
So I can't really define the columns because the JSON output is dynamic and that's why I want to preprocess it in PHP first.
No matter how you approach this, there's going to be some significant data-formatting required.
Best approach for what you're asking: use DataTables server-side tools.
It requires including some additional components, but will simplify the javascript down to:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
...with a little tweaking, you can simplify that further:
$(function(){
var dt = new dataTableAuto();
dt.load();
});
function dataTableAuto() {
this.params = {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
};
this.load = function() {
$('#example').DataTable( this.params );
}
}
php ajax server to send raw JSON as a single row
Simply send an ajax request to php which includes the counter, then respond with a json array matching what you want to build.
Javascript snippet
counter = 0;
$.ajax({
url: '[your url]',
type: 'post',
data: {"counter":counter},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.row.add(JSON.parse(response)).draw( false );
counter++;
},
});
php Snippet
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$counter = $data['counter'];
$totalRows = 10;
for( $i = 0; $i < $totalRows; $i++) {
$result[] = $counter .".". $i;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
DataTables pure AJAX approach
javascript
$(function(){
t = $('#example');
$.ajax({
url: '[your url]',
type: 'post',
data: {"classID":12},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.DataTable( JSON.parse(response) );
},
});
});
php
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$classID = intval($data['classID']);
$cols = array('Name', 'Position', 'Score');
foreach ( $cols as $colName ) {
$entry = new stdClass();
$entry->title = $colName;
$result['columns'][] = $entry;
}
$result = // some query [ex: get rows by class id]
foreach( $result as $row) {
$thisRow = array();
foreach ( $cols as $colName ) {
$thisRow[] = $row['$colName']
}
$result['data'][] = $thisRow;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
This should produce an object similar to:
{
data: [
['Joseph Taylor', '22', '90']
],
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Score" }
]
}