Search code examples
jqueryajaxdatatables

Sending form data to DataTables ajax call


I'm using the jQuery plugin "DataTables" to display data from my database. I have successfully configured it to make an ajax call to a PHP script that returns JSON encoded data. That all works fine and the table displays correctly.

The problem I'm running into is that I want the user to be able to fill in a form with additional search criteria. Once the user hits a submit button it would then need reload the DataTables and instead of just making an ajax call to a PHP file it would need to send the form data to the PHP file as well. That way I can use logic to return the correct JSON response.

So there are 2 issues:

  1. How to pass form data in the ajax call
  2. How to reload table on #narrowSearch click event

Wondering if anyone knows how to do this?

jQuery:

$(document).ready(function() {
    $('#table').DataTable( {
        ajax: {
            //////////////////////////////////////////////////////////////////////
            //need a way to pass #zipRefine and #milesFromZip to index-process.php
            //////////////////////////////////////////////////////////////////////
            url: 'index-process.php',
            dataSrc: ''
        },
        columns: [
            { data: 'First Name' },
            { data: 'Last Name' },
            { data: 'City' },
            { data: 'Email' }

        ]
    });
});

HTML:

<input type="text" name="zipRefine" id="zipRefine"/>
<input type="text" name="milesFromZip" id="milesFromZip"/>
<input type="submit" id="narrowSearch" value="Search By Zip Code"/>

<table id="table" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>City</th>
            <th>Email</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>City</th>
            <th>Email</th>
        </tr>
    </tfoot>
</table>

PHP index-process.php:

if(isset($_POST['zipRefine']) && isset($_POST['milesFromZip'])){
     $refinedData = array("First Name"=>"","Last Name"=>"","City"=>"","Email"=>"");
     ///query refined set of data
     echo json_encode($refinedData);
}else{
     $defaultData = array("First Name"=>"","Last Name"=>"","City"=>"","Email"=>"");
     ////query default set of data
     echo json_encode($defaultData);
} 

Solution

  • this worked for me https://stackoverflow.com/a/38908085/1231402

    also to reload table this: oTable.ajax.reload(); is the working script