HoodCoderMan HoodCoderMan - 7 months ago 70
Javascript Question

Load JQUERY DATATABLE on CHANGE event

I am using this script to load the DATATABLE on READY:

function renderDataTable(serviceUrl)
{
var $dataTable = $('#example1').DataTable({
"ajax": serviceUrl,
"iDisplayLength": 25,
"order": [[2, "asc"]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true
});
});


Here is the READY event:

$(document).ready(function()
{
renderDataTable('api/service_teus.php');
});


The PHP script looks like this:

<?php
$select = "SELECT SERVICE, SIZE_TYPE, TEUS FROM table";
$query = mysqli_query($dbc, $select) or die(mysqli_error());

$out = array();
while($row = $query->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
mysqli_free_result($query);
?>


All the above code works fine. The datatable loads when the page is ready, and the datatable works like how it's supposed to.

What I need to do is create the ability for the user to reload the datatable when a new option is selected in a dropdown with an ID #serviceload.

So I remove the READY event.

Now, in the JAVASCRIPT, I create a CHANGE event:

$('#serviceload').change(function()
{
var page = $('#serviceload').val(); // user selection

var $dataTable: $('#example1').DataTable({ // datatable
"ajax": "api/service_teus.php", {page: page}, // here is where I think the problem lies
"data": data,
"iDisplayLength": 25,
"order": [[2, "asc"]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true
});
});


More than likely, I'm guessing the error is in the ajax call above.

I alter the PHP script slightly to look like this:

<?php
if($_POST['page'] == true)
{
$service = mysqli_real_escape_string($dbc, $_POST['page']);
$select = "SELECT SERVICE, SIZE_TYPE, TEUS FROM table WHERE SERVICE - '$service'";
$query = mysqli_query($dbc, $select) or die(mysqli_error());

$out = array();
while ($row = $query->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
mysqli_free_result($query);
}
?>


I am not sure if I using the AJAX call correctly in the javascript directly above.

If you see the error, please help.

Thank you, fellow coders.

Answer

So, after 2 weeks of research, I finally found the solution to my problem.

Since I already had a HTML dropdown in place, in the READY event, I added this:

 var table = $('#example1').DataTable();
 $('#serviceload').on('change', function(){
   table.columns(1).search( this.value ).draw();
 });

Which I found here: http://jsfiddle.net/Ratan_Paul/5Lj6peof/1/

And now, when the CHANGE event is fired, the new data is populated without sending a variable to the server, which is what I was trying to do in my initial code above.