Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables read ajax response with your own parameters

Using DataTables 1.10.15 in Server Side mode. I've created a PHP script to provide a JSON response which includes the parameters they mention in the documentation: https://datatables.net/manual/server-side#Returned-data

I want to add my own parameters to the JSON response, e.g.

$response = [
    'data' => [ ], // Required by DataTables 
    'form_errors' => [ ] // Not required by DataTables
];
echo json_encode($response);

The js which I have for the ajax call looks like this:

var myTable = $('#myTable').DataTable( {
    "serverSide": true,
    "ajax": { 
        "url" : "/response.php",
        "method" : "POST"
    },
});

How can I read the ajax response? I've seen in the API that there is a .on('xhr') method (https://datatables.net/reference/event/xhr) which fires when the ajax request has been completed, e.g.

var myTable = $('#myTable').DataTable( {
    "serverSide": true,
    "ajax": { 
        "url" : "/response.php",
        "method" : "POST"
    },
}).on( 'xhr.dt', function () {
    // Read response here?
});

But I cannot find a way to read the ajax response data at that point.

Does anyone know if this is possible?

like image 972
Andy Avatar asked Jun 29 '17 10:06

Andy


People also ask

What is dataSrc?

dataSrc( data ) Description: As a function dataSrc provides the ability to manipulate the data returned from the server from one form into another. For example, if your data is split over multiple arrays you might combine it into a single array to return for processing and display by DataTables.

What is Ajax in Javascript with example?

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


1 Answers

Old question, but i'll try to answer may need for future, because i have exactly same problem and after looking for their documentation i found drawCallback.

From your code:

var myTable = $('#myTable').DataTable( {
    "serverSide": true,
    "ajax": { 
        "url" : "/response.php",
        "method" : "POST"
    },
    "drawCallback": function (settings) { 
        // Here the response
        var response = settings.json;
        console.log(response);
    },
});
like image 167
Idham Perdameian Avatar answered Oct 22 '22 14:10

Idham Perdameian