0
votes

I need to send a parameter to server side processing by the selecting an option in list and the retrieve only the records that match the selection.

1) Javascript: What is the best way to send a parameter?

2) PHP: How can I get the value received and filter the array?

Html

<div class="form-group">
    <label for="title">Pick Name:</label>
    <select name="iname" class="form-control" onchange="showUser(this.value)" style="width:500px">
        <option value="Fred">Fred</option>
        <option value="Lucy">Lucy</option>
        <option value="Amy">Amy</option>
        <option value="Joe">Joe</option>
    </select>
</div>

Javascript

function showUser(str){             
    $('#mytable').DataTable({
        "bProcessing": true,
        "sAjaxSource": "go1.php",           
        "aoColumns": [
                        { mData: 'Name' },
                        { mData: 'Start Date' },
                        { mData: 'End Date' },
                        { mData: 'Notes' }          
                       ]
    });
};

PHP

$data = array(
        array('Name'=>'Lucy', 'Start Date'=>'2017-11-01', 'End Date'=>'2017-11-01', 'Notes'=>'Notes02'),
        array('Name'=>'Amy',  'Start Date'=>'2017-09-01', 'End Date'=>'2017-09-11', 'Notes'=>'Notes03'),
        array('Name'=>'Fred', 'Start Date'=>'2017-02-03', 'End Date'=>'2017-02-04', 'Notes'=>'Notes04'),
        array('Name'=>'Joe',  'Start Date'=>'2017-03-05', 'End Date'=>'2017-03-21', 'Notes'=>'Notes05')
);

$results = array(
    'sEcho'=>'1',
    'iTotalRecords'=>count($data),
    'TotalDisplayRecords'=>count($data),
    'aaData'=>$data
);

echo json_encode($results);

Regards, Elio Fernandes

1
Mark, I copied the line code with 'fnServerParams' and in the php file I just tried to echo ($_GET["UserName"]) and I get the error: Invalid Json Response. What am I missing?Elio Fernandes

1 Answers

0
votes

To pass custom parameters in the datatables request you can use fnServerParams which you add to the datatables initialisation code, like this:

$('#mytable').DataTable({
    "bProcessing": true,
    "sAjaxSource": "go1.php",  
    "fnServerParams": function (aoData) {
        aoData.push({ "name": "UserName", "value": $('[name="iname"]').val() });    
    },          
    "aoColumns": [
                    { mData: 'Name' },
                    { mData: 'Start Date' },
                    { mData: 'End Date' },
                    { mData: 'Notes' }          
                   ]
});

Every time the datatable draws, the new parameter will also be passed. On the server-side, you need to get the new custom parameter from the querystring, which in PHP I believe is $_GET["UserName"].

Note that you're using datatables v1.9 syntax, so my example does the same (even though you use the uppercase Datatables to initialise). If you want to use v1.10 then use ajax.data, the syntax is a bit different.