Load dataTable. Successful AJAX request, but no data visible - php

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");
}
},
});
});

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 ');
}
});

How to send ajax request in Datatables in Codeigniter

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

Problem with json data source on ui autocomplete

I have a problem with my code. I receive data via ajax and it works, but the problem is that when I try to search for an element and all the elements appear so the search does not work properly.
JS code :
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
PHP code :
$data = array();
while($line = mysqli_fetch_object($liste_grp) ){
$data[] = array("label"=>$line->grp_nom,"value"=>$line->grp_nom ,"id"=>$line->groupement_id);
}
echo json_encode($data);
result
you should send the text you are searching for to ajax request so your autocomplete function should be
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque ,
term: request.term
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
request.term is your search text and in your example it is group text
and also you need to modify your mysql query and add condition (like)
for example
$rs = mysql_query("SELECT * FROM table WHERE colum LIKE '%" . $_POST['term'] . "%'");
and finally you can check https://jqueryui.com/autocomplete/#remote-jsonp
I would advise the following jQuery:
$( "#grp_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id: request.term
},
success: function( data ) {
console.log(data);
response(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
This is a small change. This will send the request.term to your PHP Script. For example, if the user types "gro", this will be sent to your script and would be accessed via:
$_POST['marque_id']
This would assume your SQL Query is something like:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE '?%'");
$stmt->bind_param("s", $_POST['marque_id']);
$stmt->execute();
$liste_grp = $stmt->get_result();
$data = array();
while($line = $liste_grp->fetch_assoc()) {
$data[] = array(
"label" => $line['grp_nom'],
"value" => $line['grp_nom'],
"id" => $line['groupement_id']
);
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($data);
This uses the MySQLi Prepared Statement, and will help prevent SQL Injection. I also included the JSON Header as good practice. The result of search "gro" would be something like:
[
{
"label": "GROUPE DATAPNEU TEST",
"value": "GROUPE DATAPNEU TEST",
"id": 1
}
];
Thanks guys i found a solution it works better
i used tokeninput with many options
http://loopj.com/jquery-tokeni
$.ajax({
url:"ajax_get_societe_authorisation",
method:"POST",
scriptCharset: "iso-8859-1",
cache: false,
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
console.log(data);
$("#soc_name").tokenInput(data
,{
tokenLimit: 1,
hintText: "Recherche une société par son nom",
noResultsText: "Aucune société trouvé",
searchingText: "Recherche en cours ...",
onAdd: function (data) {
$("#soc_id").val(data.id);
},
onDelete: function (item) {
$("#soc_id").val("");
}
}
);
}
});

xeditable select2 remote data fetching into a select field

I am trying to implement xeditable plugin select2 with emote data fetch from my database , my data fetch script is returning the json data but the ajax call is not retrieving it . my code looks like the following:
HTML
found by ID
Javascript
$('#username ').editable({
type: 'select2',
url: '../payments/person.php',
pk: 1,
onblur: 'submit',
emptytext: 'None',
select2: {
placeholder: 'Select a Requester',
allowClear: true,
width: '230px',
minimumInputLength: 3,
id: function (e) {
return e.person_id;
},
ajax: {
url: '../payments/person.php',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
formatResult: function (employee) {
return employee.name;
},
formatSelection: function (employee) {
return employee.name;
},
initSelection: function (element, callback) {
return $.get('../payments/person.php', { query: element.val() }, function (data) {
callback(data);
}, 'json'); //added dataType
}
}
});
Php code returns the data in json format like below:
[{"id":"1","name":"AdminAdmin"}]
I am sure my ajax code is not collecting the data properly , and when i click on it it doesnt load the popup as well. if someone could help.
my php code for fetching look like the following:
if (isset($_POST['person_id'])) {
$id = trim($_POST['person_id']);
$result = array();
$id = mysqli_real_escape_string($con,$id);
$res = mysqli_query($con,"SELECT person_id,Concat(first_name ,last_name) as name FROM k_people ");
while ($row = mysqli_fetch_array($res)) {
$result[] = array(
'id' => $row['person_id'],
'text' => $row['name']
);
}
echo json_encode($result);
}
I think [{"id":"1","name":"AdminAdmin"}] should be [{"id":"1","text":"AdminAdmin"}].

How to post the parameter in ajax call of jquery datatable

As of now I am passing parameter along with URL in ajax call of data table.
But I want to pass it as POST method, please anyone one help me regarding parameter passing in post method, here's my trial code:
// Sending through GET
var $table = $('#example').dataTable(
"processing": true,
"serverSide": true,
"bDestroy": true,
"bJQueryUI": true,
"ajax": 'getResult.php?formName=afscpMcn&action=search&mcn_no='+mcnNum+'&cust_nm='+cust_num+'&emp_id='+emp+''
});
Just pass it like a normal jQuery ajax in POST fashion.
The structure should look like this:
ajax: { type: 'POST', url: <path>, data: { your desired data } }
Example:
var $table = $('#example').dataTable(
"processing": true,
"serverSide": true,
"bDestroy": true,
"bJQueryUI": true,
"ajax": {
'type': 'POST',
'url': 'getResult.php',
'data': {
formName: 'afscpMcn',
action: 'search',
// etc..
},
}
});
In PHP, just access the POST indices as usual (just the straightforward approach):
getResult.php
$form_name = $_POST['formName'];
// the rest of your values ...
DataTables manual entry
You can try this way:
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"data": function ( d ) {
d.extra_search = $('#extra').val();
}
}
});
https://datatables.net/reference/option/ajax.data
$("#tbl").dataTable({
oLanguage: {
sProcessing: '<div id="loader"></div>'
},
bProcessing: true,
"bServerSide": true,
"iDisplayLength": pageSize,
"sAjaxSource": " /PurchaseOrder/AddVendorItems", // url getData.php etc
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
aoData.push({ "name": "where", "value": ID +" AND ISNULL(IsFinal,0) = "+ ($("#chkFinal").bootstrapSwitch('state') == true ? 1 : 0) });
aoData.push({"name": "PackIDFK", "value": $("#PackIDFK").val()}) //pushing custom parameters
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
} );
} });
This is real time example.The aoData contains all the parameters which is required on server side and you can also push your own custom parameters

Categories