How to send ajax request in Datatables in Codeigniter - php

I Have used this ignited_datatables https://github.com/IgnitedDatatables/Ignited-Datatables in my CodeIgniter project. It successfully returns data from the database. But the main problem is that when I add a new record the newly inserted data is not shown in the table automatically and when I refresh the page then the newly inserted data is then shown in the table. so I want to show that data automatically through ajax and I have not to refresh the page.
My View
<div class="box-body table-responsive">
<table id="Slider_table" class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>item_Price</th>
<th>Description</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div><!-- /.box-body -->
This Script is Inside the View
$(document).ready(function() {
$("#Slider_table").dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxDataProp": "data",
"fnServerData": function(sSource, aoData, fnCallback){
$.ajax({
"dataType": "json",
"type" : "POST",
"url" : "'.base_url().'Home/items_list/list",
"data" : aoData,
"success" : function(res){
fnCallback(res);
}
});
}
});
});

I think you need to use draw() method after success in order to have the table's display updated.
table.row.add( {
//you dynamic data
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
} ).draw();
as per documentation. please refer draw()

You can use ajax.reload() method
var i=1;
function datatable()
{
$("#myTable1").dataTable().fnDestroy();
$('#myTable1').DataTable({
"ordering": true,
"searching": true,
"bPaginate": true,
ajax: 'myajaxURL.php',
columns : [
{ "render": function ( data, type, full, meta ) { return i++; }
},
{"data": "col1"},
{"data": "col2"},
{"data": "col3"},
]
});
}
function insertData {
//after each insertion do this
var i=1;
$('#myTable1').DataTable().ajax.reload();
//after each insertion do this
}
$(document).ready(function () {
datatable();
});

i always did this in every view of my page
var table;
table = $('#Slider_table').dataTable({
"bPaginate": false,
"bLengthChange": false,
"bFilter": false, // OPTIONAL
"bSorting": false,
"bInfo": true,
"bAutoWidth": false,
});
function getData() {
$.ajax({
type: "POST",
url: "<?php echo base_url('your_controler/function_name'); ?>",
data: aoData,
error: function(response) {
alert('Error')
},
success: function(response) {
setTable(response);
}
});
}
function setTable(response) {
var obj = JSON.parse(response);
var t = $('#Slider_table').dataTable();
t.clear().draw();
$.each(obj, function(index, value) {
var a = value.a;
var b = value.b;
var c = value.c;
t.row.add([
a,
b,
c
]).draw(false);
})
}
So everytime you reload or insert a new data,you just have to call getData() function to load a new set of data you just insert. And t.clear().draw(); will clear all data from tbody,and replaced it with new one . Hope this helps

Related

edit and delete button Add in server side data table in php ,ajax

I put edit a button but how can I pass id of each row.
Its server side data table but I don't know how get id for edit and button
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"packing-grid-data.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
},
},
"columnDefs": [
{
"data": null,
"defaultContent": "<a href='view_product.php?id=' name='edit' class='btn btn-primary'> VIEW </a>",
"targets": -1
}
]
});
});
</script>
There are two ways you can do this:
You can prepare the Edit and Delete button html in the PHP code and pass it in ajax response
Using datatable jquery createdRow callback.Check below code. In the code data[1] means id value from database.
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"packing-grid-data.php",
type: "post",
error: function(){
$(".employee-grid-error").html("");
$("#employee-grid").append('No data found in the server');
$("#employee-grid_processing").css("display","none");
},
},
"columnDefs": [
{
"data": null,
"targets": -1
}
],
createdRow : function( row, data, dataIndex ) {
$( row ).find('td:eq(-1)').html(' VIEW ');
}
});

jquery ajax datatable error

I am getting this error:
DataTables warning: table id=discount_html - Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
My code is:
$('#abcd').DataTable({
"processing":true,
"serverSide":true,
"destroy" : true,
"order":[],
"pageLength": 50,
"columnDefs": [
{ "orderable": false, "targets": 0 }
],
"ajax":{
url: 'abc.php',
type:"POST",
"data": function(d){
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
},
dataSrc: function (json) {
var return_data = new Array();
if(json.data.length > 0){
var obj = json.data;
console.log(obj);
return obj;
}
return return_data;
},
"columns" : [
{'data':'input'},
{'data': 'date'},
{'data': 'id'},
{'data': 'pname'},
{'data': 'cname'},
{'data': 'clname'},
{'data': 'dname'},
{'data': 'act'}
]
},
});
This is my AJAX response:
"draw":1,
"recordsTotal":1073,
"recordsFiltered":1073,
"data":[
{
"input":"<input data-id = "0" type="checkbox" name="report[]" class="allCheck" value="1234">",
"date":"2018-01-29",
"id":"1244",
"pname":"XYZ",
"cname":"adasdasd",
"clname":"NA",
"dname":"asdasdasdas",
"act":"hgh"
},
{
"input":"<input data-id = "1" type="checkbox" name="report[]" class="allCheck" value="23232">",
"date":"2018-01-29",
"id":"23232",
"pname":"aaaaa",
"cname":"asdasdsadasdsa",
"clname":"ewqweqewq",
"dname":"aaaaaaaa",
"act":"hgh"
},
and below is the HTML:
<tr>
<th><input type="checkbox" name="" id="checkAll"></th>
<th class="recept_td01">Date </th>
<th class="recept_td03">Code</th>
<th class="recept_td04">Name</th>
<th class="recept_td05">Ce</th>
<th class="recept_td05">Cli</th>
<th class="recept_td06">Doc</th>
<th class="recept_td07" id="action">Action</th>
</tr>
What am I doing wrong, that I am getting that error, tried everything but nothing seems to be working.

Load dataTable. Successful AJAX request, but no data visible

How do I load json data with serverside processing in a dataTable?
I'm trying to build a custom Wordpress plugin and display results from wpdb inside a dataTable.
I get a successful AJAX return call, but the dataTable only shows a "Processing..." stage and the table does not fill the rows (keeps empty).
Although I have read many(!) similar problems and answers here, any help to load data with ajax and json_encode is much appreciated.
The current code:
dahsboard.php
<table id="table-id" cellpadding="1" cellspacing="1" width="100%">
<thead><tr>
<th>h_id</th>
<th>h_subject</th>
</tr></thead>
ajax-grid-data.php
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback(){
global $wpdb;
$query = "SELECT h_id, h_subject FROM wp_tablename ORDER BY h_id limit 3";
$myrows = $wpdb->get_results($query);
foreach ($myrows as $value) {
$ResultData['h_id'] = $value->h_id;
$ResultData['h_subject'] = $value->h_subject;
$data[] = $ResultData;
}
$json_data = array(
"draw" => 1,
"recordsTotal" => 3,
"recordsFiltered" => 3,
"data" => $data,
);
echo json_encode($json_data);
die();
}
I think that the problem is in datatype formatting underneath:
dashbboard.js
var oTable;
jQuery(document).ready(function() {
jQuery.fn.dataTable.ext.errMode = 'throw';
oTable = jQuery('#table-id').DataTable( {
"serverSide": true,
"processing": true,
"columnDefs": [{"defaultContent": "-","targets": "_all"}],
"columns": [
{ "data": "h_id" } ,
{ "data": "h_subject" }
],
"ajax":{
url: "admin-ajax.php?action=my_action",
type: "post",
dataSrc:'',
dataType : "json",
contentType: "application/json; charset=utf-8",
//dataSrc: function(data){ return data.data; },
//async : false,
//processData: true,
//accepts: {json: "application/json, text/javascript"},
success: function(data){
console.log(JSON.stringify(data)); // successful echo data objects are shown in dashboard.
},
error: function(){
jQuery("#tablename").append('<tbody class="grid-error"><tr><th colspan="2">No results.</th></tr></tbody>');
jQuery("#tablename_processing").css("display","none");
}
},
});
});
Current results
Result php file test: .../wp-admin/admin-ajax.php?action=my_action
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"h_id":"37168","h_subject":"6216"},{"h_id":"37169","h_subject":"7021"},{"h_id":"37170","h_subject":"8923"}]}
Result ajax success function, console data:
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"h_id":"37168","h_subject":"6216"},{"h_id":"37169","h_subject":"7021"},{"h_id":"37170","h_subject":"8923"}]}
Result dashboard table only shows: processing...
Deleting the dataSrc and success function did wonders and fills up the dataTable with data. I really appreciate the help and efforts of #bassxzero and #davidkonrad.
Ensuring that there is an answer, "on behalf of" the new version of dashboard.js:
var oTable;
jQuery(document).ready(function() {
jQuery.fn.dataTable.ext.errMode = 'throw';
oTable = jQuery('#table-id').DataTable( {
"serverSide": true,
"processing": true,
"columnDefs": [{"defaultContent": "-","targets": "_all"}],
"columns": [
{ "data": "h_id" } ,
{ "data": "h_subject" }
],
"ajax":{
url: "admin-ajax.php?action=my_action",
type: "post",
dataType : "json",
contentType: "application/json; charset=utf-8",
error: function(){
jQuery("#tablename").append('<tbody class="grid-error"><tr><th colspan="2">No results.</th></tr></tbody>');
jQuery("#tablename_processing").css("display","none");
}
},
});
});

"Add to cart" ajax button on DataTable

I am started to use DataTables because they provide what I need: ready to use pagination, ready to use how many items to show on the table 10, 25 .. etc. And here is the first problem. I want to put one button Add to cart at the end and with ajax to place items in basket which will downloaded later as zip. So far I was able to put the button but I'm very new in ajax and jquery stuff and can't figured out how to do the cart things. Here is what I have:
The table:
<table id="example" class="display table table-striped table-bordered responsive">
<thead>
<tr>
<th>№</th>
<th>Program</th>
<th>Title</th>
<th>Description</th>
<th>Add to Cart</th>
</tr>
</thead>
Here is how I put the custom button at the end
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "response.php",
"aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Add to cart';
}
}]
});
});
How I trying to put them in the cart
$(document).ready(function(){
$.ajax({
type:'post',
url:'store_items.php',
data:{
total_cart_items:"totalitems"
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
});
function cart(id)
{
var ele=document.getElementById(upload_id);
var upload_title=document.getElementById("upload_title").value;
var upload_description=document.getElementById("upload_description").value;
$.ajax({
type:'post',
url:'store_items.php',
data:{
upload_title:upload_title,
upload_description:upload_description
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
}
function show_cart()
{
$.ajax({
type:'post',
url:'store_items.php',
data:{
showcart:"cart"
},
success:function(response) {
document.getElementById("mycart").innerHTML=response;
$("#mycart").slideToggle();
}
});
}
and the php part
session_start();
if(isset($_POST['total_cart_items']))
{
echo count($_SESSION['upload_title']);
exit();
}
if(isset($_POST['upload_title']))
{
$_SESSION['upload_title'][]=$_POST['upload_title'];
$_SESSION['upload_description'][]=$_POST['upload_description'];
echo count($_SESSION['upload_title']);
exit();
}
if(isset($_POST['showcart']))
{
for($i=0;$i<count($_SESSION['upload_title']);$i++)
{
echo "<div class='cart_items'>";
echo "<p>".$_SESSION['upload_title'][$i]."</p>";
echo "<p>".$_SESSION['upload_description'][$i]."</p>";
echo "</div>";
}
exit();
}
So far the main problem that I see is how to pass the ID of the item which I store in cart. On the datatable ID of the item is on the first №. Then I'm not sure how to pass it to the cart with this ajax.
If need I can show also the php part of response.php from where the table is populated.
For your MAJOR problem with getting ID you can make this:
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "response.php",
"aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function(data, type, full) {
return '<a class="btn btn-info btn-sm" href=#' + full[0] + '>' + 'Add to Cart' + '</a>';
}
}
}]
});
});
The mRender Function takes three parameters:
data = The data for this cell, as defined in mData
type = The datatype
(can be ignored mostly)
full = The full data array for this row.

create datatables jquery dynamically with parameter from query

I use "datatables plugin for jquery" to display the results of a query in mysql.
The user can also select from a dropdown list (dateParam) and a multiselect values (conseiller) that will automatically restrict the results of the query and thus modify the table. Instead of having 5 columns, I have only 3 for example.
This is where I get the following error alert: "... requested unknown parameter 'data.1' (for example) for row 0...".
json result without selecting:
[{"name":"CONSEILLER","data":["cons1","cons2","cons3","TOTAL UNITES"]},{"name":"TOTAL UNITES","data":[1,9,2,12]}]
json result if I select some parameters:
[{"name":"CONSEILLER","data":["cons2","TOTAL UNITES"]},{"name":"TOTAL UNITES","data":[9,9]}]
Here a part of my query :
<?php
include("../dbconfig.php");
if (isset($_GET["dateParam"],$_GET["dateParam2"],$_GET["conseiller"])) {
$SQL = "
...the query...
";
$result = $dbh->prepare($SQL);
$result->execute();
} else {
$SQL = "
...the query....
";
$result = $dbh->prepare($SQL);
$result->execute();
}
$rows = array();
$rows['name'] = 'CONSEILLER';
$rows1 = array();
$rows1['name'] = 'TOTAL UNITES';
while($row = $result->fetch()) {
$rows['data'][] = $row['CONSEILLER'];
$rows1['data'][] = ($row['UNITES']);
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
header('Content-type: application/json');
print json_encode($result, JSON_NUMERIC_CHECK); // VERSION PHP >= 5.3.3
?>
Here is a part of my js :
$(document).ready(function() {
var table = $('#dt_actions_rae_conseiller').DataTable({
"paging": false,
"searching": false,
"bInfo": false,
"scrollX": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxDataProp": "",
"sAjaxSource": "../query/query_actions_rae_conseiller_dt.php",
"aoColumns": [
{ "data": "name" },
{ "data": "data.0" },
{ "data": "data.1" },
{ "data": "data.2" },
{ "data": "data.3" },
],
});
});
/**
* Datepicker
*/
$(function() {
var dateParam = "";
$( "#datepicker" ).datepicker({
dateFormat: "yy-mm-dd",
showAnim: 'drop',
//showOn: "button",
//buttonImage: "../icones/calendar.gif",
//buttonImageOnly: true,
onSelect: function(date){
dateParam = date;
}
});
var dateParam2 = "";
$( "#datepicker2" ).datepicker({
dateFormat: "yy-mm-dd",
showAnim: 'drop',
//showOn: "button",
//buttonImage: "../icones/calendar.gif",
//buttonImageOnly: true,
onSelect: function(date){
dateParam2 = date;
}
});
});
/**
* Multiselect
*/
$(function(){
$("#conseiller").multiselect({
//header: 'Choisir conseillers',
minWidth: 160,
checkAllText: 'all',
uncheckAllText: 'no',
noneSelectedText: 'Conseiller',
selectedList: 7,
/* selectedText: function(numChecked, numTotal, checkedItems){
return numChecked + ' of ' + numTotal + ' checked';
}, */
show: ["bounce", 200],
hide: ["explode", 1000]
});
//$('#projet').bind('change', function() {alert('Change'); });
});
/**
* Button
*/
$(function(){
$('button').click(function() {
var d1 = $("#datepicker").val();
var d2 = $("#datepicker2").val();
var d3 = $("#conseiller").val().join(",");
$.ajax({
url: "../query/query_actions_rae_conseiller_dt.php",
//data: {dateParam:d1, dateParam2:d2},
type: "get",
dataType: "json",
success: function(json){
table = $('#dt_actions_rae_conseiller')
.on('preXhr.dt', function ( e, settings, data ) {
data.dateParam = d1
data.dateParam2 = d2
data.conseiller = d3
})
.DataTable({
"destroy": true, // TO REINITIALISE DATATABLE
"paging": false,
"searching": false,
"bInfo": false,
"scrollX": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxDataProp": "",
"sAjaxSource": "../query/query_actions_rae_conseiller_dt.php",
"aoColumns": [
{ "data": "name" },
{ "data": "data.0" },
{ "data": "data.1" },
{ "data": "data.2" },
{ "data": "data.3" },
],
});
} // end ajax function
}); // end ajax
}); // end click function
}); // end function
and my php:
<table id="dt_actions_rae_conseiller" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead> // not needed ?
<tr> // not needed ?
<th></th> // not needed ?
<th></th> // not needed ?
<th></th> // not needed ?
<th></th> // not needed ?
<th></th> // not needed ?
</tr> // not needed ?
</thead> // not needed ?
</table>
Thnaks for all !
Ahem, as Php . net says is not sure to test it whit a rowcount -> http://php.net/manual/en/pdostatement.rowcount.php
Because most databases won't return the number of rows.
Instead you can first run a query A with a count(*) then use a fetchColumn to have in a var the number of rows that will be obtained and then do your loop only if count > 0

Categories