JQuery DataTables - Catch 'ajax' response - php

I have an web-application that uses JQuery DataTables. It uses the ajax parameter for requesting and inserting JSON data into the table.
However, at the top of the requested .php file it is checked whether the user is logged in. If this check fails it echoes a JSON notice.
<?php
session_start();
if (!isset($_SESSION['logged']) || $_SESSION['logged'] !== true) {
$array = array(utf8_encode('logged')=>utf8_encode('false'));
echo json_encode($array);
exit;
}
?>
table = $('#active-issues').DataTable({
"scrollY": pixels,
"dom": '<"top"if>rt<"bottom"><"clear">',
"paging": false,
"responsive":true,
"bProcessing": true,
"ajax": {
"data": function(){
$('#active-issues').DataTable().ajax.url(
"php/get_issues.php"
+ "?id=" + id
+ "&customer_id=" + customerid
);
}
},
columns: [
{ responsivePriority: 1 },
{ responsivePriority: 2 },
{ responsivePriority: 4 },
{ responsivePriority: 3 },
{ responsivePriority: 5 },
{ responsivePriority: 6 },
{ responsivePriority: 7 }
],
"columnDefs": [
{ "type": "alt-string", targets: 5},
{ "type": "alt-string", targets: 6},
]
});
table.ajax.reload(null, false);
Is it possible to catch the response given to JQuery DataTables? So that I can check whether result is { logged: "false" } and act accordingly?

Took a while and the help of 'allan' from datatables forums. But the problem is finally solved.
via dataSrc it's possible to manipulate the ajax result before it is printed in the table, I, however, used it to check whether the result contains logged and whether it equals to false and act accordingly if it does:
"ajax": {
"data": function(){
$('#active-issues').DataTable().ajax.url(
"php/get_issues.php?id=" + id + "&customer_id=" + customerid
);
},
"dataSrc": function ( json ) {
if(typeof json['logged'] != "undefined") {
if (json['logged'] == 'false') {
location.replace('php/logout.php');
}
}
return json.aaData;
}
},

Yes, this can be done if you do your ajax cal externally i.e perform an independent ajax request to obtain the response and the identify if the response contains
{ logged: "false" } and the populate the data to the data table accordingly.

Related

Change td type in ajax-loaded datatable [duplicate]

I am trying to make a column as hyperlink with datatable but no success.
function successCallback(responseObj){
$(document).ready(function() {
$('#example').dataTable( {
"data":responseObj ,
"bDestroy": true,
"deferRender": true ,
"columns": [
{ "data": "infomation" },
{ "data": "weblink" },
]
} );
} );
}
I need the weblink to display the link and be an hyperlink in that column so users can click and be redirected to another page. I looked into render but with less information there on links, i can't succeed to do it.
I also looked into this example but it wasn't very helpful.
Use columns.render API method to dynamically produce content for a cell.
$('#example').dataTable({
"data": responseObj,
"columns": [
{ "data": "information" },
{
"data": "weblink",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '' + data + '';
}
return data;
}
}
]
});
See this example for code and demonstration.
If you are looking to add link based on other column data then can use the below approach.
$('#example').dataTable({
"data": responseObj,
"columns": [
{ "data": "information" },
{
"data": "weblink",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '' + data + '';
}
return data;
}
}
]
});
I have just changed the render function. data refers to only current column data, while row object refers to entire row of data. Hence we can use this to get any other data for that row.
$('#example').dataTable( {
"columnDefs": [ {
"targets": 0,
"data": "download_link",
"render": function ( data, type, full, meta ) {
return 'Download';
}
} ]
} );
From the documentation. It is quite clear and straightforward to me, what is it specifically that you do do not understand? What errors do you see?
For a more complete example, see here
in my example I make the column cell fully clickable and not just the text inside the column. I think it will be useful for someone. use bootsrap 5
$(document).ready(function() {
$('#datatable').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('get.profiles') !!}',
columns: [
{
data: 'id',
name: 'id',
render : function(data, type, row, meta) {return'<a class=" d-inline-block fw-normal w-100 h-100 pe-auto" href="profiles/edit/' + row.id + '">' + row.id + '</a>';},
},
{
data: 'name',
name: 'name',
render : function(data, type, row, meta) {return'<a class="d-inline-block fw-normal w-100 h-100 pe-auto" href="profiles/edit/' + row.id + '">' + row.name + '</a>';},
},
]
});
});
in your css file add
td{
height: 100%;
overflow: visible;
}

jQuery function not calling on modal close

I want to call a function that processes my datatable at the serverside when I close a bootstrap modal.
This is my jquery
$('#launch').on('hidden.bs.modal', function () {
fill_datatable();
console.log(123);
});
console.log(333);
function fill_datatable(filter_status = ''){
var dataTable = $('#dataTable2').DataTable({
"processing" : true,
"pageLength": 25,
"columnDefs": [
{ "searchable": true, "targets": 0 }
],
"serverSide" : true,
"createdRow": function(row, data, index) {
switch (data[8]) {
default:
$(row).css('background-color', 'white');
}
},
"order" : [],
"ajax" : {
url:"ajax/fetch.php",
type:"POST",
data:{ filter_status:filter_status }
},
"columnDefs": [
{ "width": "40%", "targets": 3,
"className": "text-justify", "targets": 3,
"searchable": true, "targets": 3,
}
]
});
}
When the modal closes I can see 123 in my console but it doesnt call the fill_datatable() function, which is placed directly outside of the on() method.
Note that the fill_datatable() function works because it processes the table on page load, but I want it to refresh after an action is done in the modal so I see the latest changes.
Destroy the dataTable method before calling the function, using $('#dataTable2').DataTable().destroy();
Try define function fill_datatable() before $('#launch').on('hidden.bs.modal', function () {}.

ajax is not sending data to php page

Script. I want to send data to php page:
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable({
"bProcessing": true,
"type": "POST",
"sAjaxSource": "abcd.php",
"data": [
{ game:"Football" },
{ game:"Baseball" }
],
"aoColumns": [
{ mData: 'name' } ,
{ mData: 'count' }
]
});
});
</script>
abcd.php (Data is not coming to php page):
<?php
$game=$_POST['game'];
?>
Make the value of the game: parameter an array of all the games you want.
"data": { games: ["Football", "Baseball"] },
Then in abcd.php, you can do:
$games = $_POST['games'];
This will be an array, and you can loop over it to process all the games that are requested.

DataTables - Dynamic Columns From Ajax Data Source?

I am trying to get DataTables to read the column names from an AJAX data source but it seems that there must be something that I must be missing here.
I made a fiddle fiddle in which I can manually define the data and columns that are being used by the table.
The table is declared in the HTML and there is no no need to define the column names (<thead>..</thead>):
<table id="example" class="display table table-striped table-bordered"
cellspacing="0" width="100%"></table>
In the JS we manually define the data:
var data = [
[ "Row 1 - Field 1", "Row 1 - Field 2", "Row 1 - Field 3" ],
[ "Row 2 - Field 1", "Row 2 - Field 2", "Row 2 - Field 3" ],
];
Then manually define the column names or titles:
var columns = [
{ "title":"One" },
{ "title":"Two" },
{ "title":"Three" }
];
Then when we initialise the table we simply pass the previously declared information across for DataTables to use:
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
data: data,
columns: columns
});
});
Which results in:
Now my question is how would I get this to work if the data is included in the AJAX server side response?
I have tried this in various ways and forms but nothing really seems to work out here and I am battling to find relative documentation on this.
For example if the server side processing sent back a JSON response which includes the column names at the end:
{
"data": [
{
"id": "1",
"One": "Row 1 - Field 1",
"Two": "Row 1 - Field 2",
"Three": "Row 1 - Field 3"
},
{
"id": "2",
"One": "Row 2 - Field 1",
"Two": "Row 2 - Field 2",
"Three": "Row 2 - Field 3"
}
],
"options": [],
"files": [],
"columns": [
{
"title": "One",
"data": "One"
},
{
"title": "Two",
"data": "Two"
},
{
"title": "Three",
"data": "Three"
}
]
}
Given this is the response, I tried to configure DataTables to use an AJAX data source for the row information as follows:
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
"ajax": '/test.php',
columns: columns
});
});
But obviously columns is undefined here.
So I get the column data before hand:
function getPromise() {
var deferred = $.Deferred();
var dataUrl = document.location.origin+'/text.php';
$.getJSON(dataUrl, function(jsondata) {
setTimeout(function() {
deferred.resolve(jsondata);
}, 0);
}).fail(function( jqxhr, textStatus, error ) {
// ********* FAILED
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
return deferred.promise();
}
// Get the columns
getPromise().done(function(jsondata) {
columns = jsondata.columns;
console.log(columns);
});
And pass it to DataTables as above. But this time all I get when running the example is an error in the console saying TypeError: p is undefined.
So then how could I make use of the dynamically generated columns that are being returned within the server side response? Is there not a simpler way to achieve this?
EDIT:
DataTables Editor code for server side processing / to generate the JSON response mentioned above:
<?php
// DataTables PHP library
require_once '/path/to/DataTables.php';
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
$out = Editor::inst( $db, 'example' )
->fields(
Field::inst( 'id' )->set(false),
Field::inst( '`One`' )->validator( 'Validate::notEmpty' ),
Field::inst( '`Two`' )->validator( 'Validate::notEmpty' ),
Field::inst( '`Three`' )->validator( 'Validate::notEmpty' )
)
->process( $_POST )
->data();
// On 'read' remove the DT_RowId property so we can see fully how the `idSrc`
// option works on the client-side.
if ( Editor::action( $_POST ) === Editor::ACTION_READ ) {
for ( $i=0, $ien=count($out['data']) ; $i<$ien ; $i++ ) {
unset( $out['data'][$i]['DT_RowId'] );
}
}
// Create the thead data
if (count ($out) > 0) {
$columns = array();
foreach ($out['data'][0] as $column=>$relativeValue) {
// Add all but the id value
if ($column !== 'id') {
// Add this column name
$columns[] = array(
"title"=>$column,
"data"=>$column
);
}
}
}
// Add the the thead data to the ajax response
$out['columns'] = $columns;
// Send the data back to the client
echo json_encode( $out );
If you don't use the built in DataTables ajax it should be easy enough given the structure of your data:
$(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data: {
json: JSON.stringify(jsonData)
},
success: function(d) {
$('#example').DataTable({
dom: "Bfrtip",
data: d.data,
columns: d.columns
});
}
});
});
Like this JSFiddle, you're limited then to loading all the data at once but that shouldn't be a huge issue... unless you alter it get the columns from the initial ajax call and once the DataTable is initiated then add the built-in ajax - I've not tried this though...
You must create the table in html without header
<table id="tablaListadoExpediciones" class="table table-bordered table-striped dt-responsive"> </table>
Now you have to generate the columns array dynamically. In this way, the columns will always be generated automatically even if the AJAX response varies over time.
function PintarTablaDinamicamente(datos) {//object "datos" comes from AJAX response
//I take the keys of the object as columns of the table
var arrColumnas = Object.keys(datos[0])
////In case you wanted to hide a column
//var indiceColumna = arrColumnas.indexOf("nameOfTheColumnToHide")
//if (indiceColumna !== -1) {
// arrColumnas.splice(indiceColumna, 1)
//}
var columns = []
//columns must be in JSON format-->{data:'keyToSearchInJSON',title:'columnTitle'}
for (var i in arrColumnas) {
//if (arrColumnas[i] == "SELECCIONAR") { //if you want to add a checkbox in one colunm (for example column named SELECT
// columns.push({
// data: null,
// defaultContent: '',
// className: 'select-checkbox',
// orderable: false
// });
//} else {
columns.push({ data: arrColumnas[i], title: arrColumnas[i] });
//}
}
tabla = $('#tablaListadoExpediciones').DataTable({
dom: "Blfrtip",
data: datos,
//order: [[0, 'desc']],
"pageLength": 25,
"scrollX": true,
columns: columns
,
buttons: [
{
extend: 'copy'
},
{
extend: 'excel'
},
{
extend: 'print'
}
],
//select: {
// style: 'os',
// selector: 'td:first-child'
//}
});
}

How do I iterate over a JSON array using jQuery/AJAX call from PHP? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Loop through Json object
I have a PHP function, data.php, which fetches JSON data from an external server URL like such:
<?php
$url = "https://dev.externalserver.net/directory";
$content = file_get_contents($url);
echo json_encode($content);
?>
The JSON array retrieved looks like the following:
[
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
]
I'm now trying to write an AJAX call to that PHP function, iterate through the JSON array, and display it in the browser in non-JSON formatting. My AJAX code looks like the following:
$.ajax({ url: 'data.php',
type: 'POST',
dataType: 'json',
success: function(output) {
$.each(output, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
My issue is that code is currently displaying alert boxes that show the individual characters within the array like such: 0 --> [ , 0 --> , 0 --> { ... etc etc
Is there a problem with how I'm passing the data using json_encode(); and dataType: 'json' or does the issue resolve with how I'm iterating through the array?
Thanks.
Other responders missed the sneaky but still obvious bit, that what's coming back from the resource being polled in the PHP is probably already valid JSON, and re-encoding it is causing the browser to interpret it merely as a string. In this case, the javascript never had a chance.
Remove the json_encode() bit in the PHP and just echo what comes back, and see if that doesn't improve things.
I think your problem is the this in the second each. Try:
$.each(output, function(key, value) {
$.each(value, function(key, value){
alert(key + " --> " + value);
});
});
var jsonArray = [
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
];
$.each(jsonArray, function() {
for (var key in this) {
if (this.hasOwnProperty(key)) {
console.log(key + " -> " + this[key]);
}
}
});
take a look at this
How do I loop through or enumerate a JavaScript object?

Categories