DataTables with AJAX
HTML
<script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.css">
<form id="frm">
<input type="hidden" name="param1" value="value1">
<p class="filter-container">
<b>Filter:</b><br/>
<select id="example-select" name="example_select">
<option selected>Value 1</option>
<option>Value 2</option>
<option>Value 3</option>
<option>Value 4</option>
</select>
</p>
</form>
<table id="example" class="display" cellspacing="0">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody></tbody>
</table>
CSS
.filter-container {
margin:1em 0;
padding:1em;
background-color:#F4F4F4;
border:1px solid #CCC;
}
JavaScript
// AJAX emulation
$.mockjax({
url: '/test/0',
responseTime: 200,
response: function(settings){
console.log("Request data: ", settings.data);
var val = settings.data.form.example_select;
this.responseText = {
data: [
["A01", val],
["A02", val],
["A03", val],
["A04", val],
["A05", val],
["A06", val],
["A07", val],
["A08", val],
["A09", val],
["A10", val],
["A11", val],
["A12", val]
],
draw: settings.data.draw,
recordsTotal: 1000,
recordsFiltered: 1000
}
}
});
// Converts object with "name" and "value" keys
// into object with "name" key having "value" as value
// See http://stackoverflow.com/a/12399106/3549014 for more details
$.fn.serializeObject = function(){
var obj = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name, v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
$('#example').DataTable({
"serverSide": true,
"ajax": {
"url": "/test/0",
"type": "POST",
"data": function(d){
d.form = $('#frm').serializeObject();
}
}
});
$('#example-select').on('change', function(){
$('#example').DataTable().ajax.reload();
});