Reputation: 1851
I'm using datatables with the buttons plugin. I have two buttons that filter the content that is displayed based on a variable that I need to send to the server, so the ajax url has to change everytime I click one button.
$('#example').DataTable( {
processing: true,
lengthChange: false,
dom: 'Bfrtip',
ajax: {
url: '/get?op=10',
dataSrc: ''
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'surname' },
{ data: 'phone' },
{ data: 'email' },
{ data: 'nin' }
],
buttons: [
{
text: 'Everyone',
// action ??
},
{
text: 'Owners',
},
{
text: 'Applicants',
}
],
select: true
});
The third button should reset the ajax url to the original one.
public function get_address_book_table($id, $owner = 0) {
$mysqli = $this->aet->getAetSql();
$mysqli->set_charset('utf8');
switch ($owner) {
case 0: $a = $b = NULL; break;
case 1: $a = 'pd.applicant_id'; $b = 'INNER JOIN property_demand pd ON pd.applicant_id = ab.id'; break;
case 2: $a = 'po.owner_id'; $b = 'INNER JOIN property_owner po ON po.owner_id = ab.id'; break;
}
$query = 'SELECT ab.*, sab.*' . $a . '
FROM address_book ab
INNER JOIN staff_address_book sab ON sab.contact_id = ab.id' .
$b . '
WHERE sab.staff_id = ?';
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($id, $name, $surname, $phone, $email, $nin, $note, $a, $b);
$data = [];
while ($stmt->fetch()) {
$nestedData = [];
$nestedData['id'] = $id;
$nestedData['name'] = $name;
$nestedData['surname'] = $surname;
$nestedData['phone'] = $phone;
$nestedData['email'] = $email;
$nestedData['nin'] = $nin;
$data[] = $nestedData;
}
}
return $data;
}
And the get file:
// address_book table
if ($op === 10) {
$owner = isset( $_GET['owner'] ) ? (int) $_GET['owner'] : 0;
$result = $functions->get_address_book_table($staff->getId(), $owner);
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
I'm looking for an option for the button plugin that allow me to change the ajax url on click so that the table is refreshed with the new server content.
Upvotes: 0
Views: 1332
Reputation: 7464
You need to set a value in the button event, and pass that value as a parameter to the server. Finally, you probably want to trigger the ajax data reload when you click the button. Try something like this:
var filterType = 'all';
$('#example').DataTable( {
processing: true,
lengthChange: false,
dom: 'Bfrtip',
serverSide: true,
ajax: {
url: '/get',
//dataSrc: 'data',
data: function(d) {
d.op = 10;
d.filterType = filterType;
}
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'surname' },
{ data: 'phone' },
{ data: 'email' },
{ data: 'nin' }
],
buttons: [
{
text: 'Everyone',
action: function(e, dt) { filterType = 'all'; dt.ajax.reload(); }
},
{
text: 'Owners',
action: function(e, dt) { filterType = 'owner'; dt.ajax.reload(); }
},
{
text: 'Applicants',
action: function(e, dt) { filterType = 'app'; dt.ajax.reload(); }
}
],
select: true
});
Upvotes: 1