I am trying to make ajax based search but i am very new in javascript and ajax. I need sorting, filtering etc. for results so i put results into Datatables. First of all i'am using standard html form input (it is main search field):
<input type="text" class="form-control" formmethod="post" oninput="return delayExecute();" id="name" name="name" size="61" autofocus/>
It calls delayExecute() function when user put something into form. Next, one second after user is finished writing the script run ajax request. Script looks like that:
<script>
var typingTimer;
var doneTypingInterval = 700;
function delayExecute()
{
clearTimeout(typingTimer);
typingTimer = setTimeout(
function(){makeAjaxRequest(name)},
1000
);
return true;
}
function makeAjaxRequest(name) {
$('#loading')
.show()
var myrequest = $.ajax({
url: 'ajax_search',
type: 'post',
data: {name: $('input#name').val()},
ajaxSend: function() {
},
success: function(response) {
$('table#dataTables-example tbody').html(response);
},
complete:function(){
//
$('#loading')
.hide();
$('#dataTables-example').dataTable({
// "destroy": true,
"processing": true,
"aaSorting": [],
"iDisplayLength": 10,
"aLengthMenu":[[10, 15, 25, 35, 50, 100, -1], [10, 15, 25, 35, 50, 100, "All"]]
}).columnFilter(
{
aoColumns: [
{type: "null"},
{sSelector: "#mag_filter_column", type: "select"},
]
}
);
}
});
};
In Php file (ajax_request) i read data from data base. Next I use echo function to put things into table like that:
echo '<tr>';
echo '<td>'.$some_variable.'</td>';
echo '<td>'.$other_variable.'</td>';
echo '</tr>;
And table in the view looks like that:
<table class="main-search table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Col</th>
<th>War</th>
<th>Symbol</th>
<th>Name</th>
<th>Quantity</th>
<th>Descripion</th>
<th>Photo</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
This whole thing almost work. When i make search for the first time it loads everything into datatable and everything works good (pagination, sorting etc). But when i do second search (change some word for example) - ajax serch runs, it find something but the data doesn't load into datatable. I think that i need to find way to refresh datatable plugin. I tried to use datatable.clear(), datatable.destroy() and couple other things but nothing works well for me. What is the right way to do it?
My datatable plugin version: DataTables 1.10.5
jquery version: 2.1.1