I had a html table that was populated with server information. jQuery code made it possible to click on the table rows and it would follow the dynamic link based in the corresponding id in that row.
I added script that allows a search/filter function of the table that is updated without reloading the page using AJAX method. Now clicking the table rows does not follow the link.
Here are the scriipts:
Example of table (the "link" button actually works):
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0) {
$output .= '<thead>
<tr>
<th>Order Number</th>
<th>Client</th>
<th>Status</th>
<th>Samples</th>
<th>Time Stamp</th>
<th colspan="1"></th>
</tr>
</thead>';
while ($row = mysqli_fetch_assoc($result)) {
$output .= '<tbody>
<tr class="table_click" data-href="analysis_results_disp_page.php?display_results='.$row['id'].'">
<td>'.$row['order_number'].'</td>
<td>'.$row['client_name'].' <i>('.$row['company_name'].')</i></td>
<td>'.$row['order_status'].'</td>
<td>'.$row['number_of_samples'].'</td>
<td>'.$row['date1'].' <i>('.$row['time1'].')</i></td>
<td>
<a class="edittablebtn" href="analysis_results_disp_page.php?display_results='.$row['id'].'">LINK</a>
</td>
</tr>
</tbody>';
}
jQuery used for search/filtering of table:
$(document).ready(function(){
load_data();
function load_data(query) {
$.ajax({
url:"../server/search_orders.php",
method:"POST",
data:{query:query},
success:function(data) {
$('#client_database').html(data);
}
});
}
$('#search_table').keyup(function() {
var search = $(this).val();
if(search != '') {
load_data(search);
} else {
load_data();
}
});
});
And jQuery for clicking table row (the problem area):
$(document).ready(function($) {
$(".table_click").on('click-row.bs.table', function (e, row, $element) {
window.location = $element.data('href');
});
});
The event listener '$(".table_click").on()' function for opening the ajax-links are binded to all .table_click elements that are available on $(document).ready();
Once you change the content of your dom, in your case when you update the table body with ajax, the new content has no event listeners on the .table_click elements.
In your Ajax Success function you can add the listeners to the new content:
$(".table_click:not(.processed)").addClass('processed').on(...)
Excluding .processed elements and after that adding this class will help avoiding binding and calling multiple times the same event listener.