Here's snippet from my code: page.php
<input type="text" id="search_query" style="float: right" placeholder="Search" />
<div id="result"></div>
<table>
<tr>
<th><input type="checkbox" name="select_all" id="select_all" value=""/></th>
<th>Title</th>
<th>Author</th>
<th>Date Published</th>
<th>Actions</th>
</tr>
<?php
if (isset($_POST['query'])) {
$query = $_POST['query'];
$res = search_articles($query); // a function I have to query the database with SQL 'LIKE'
} else {
$res = view_articles(); // another function
}
while ($row = $res->fetch_assoc()) {
echo '<tr>';
echo '<td><input type="checkbox" name="checked_id[]" class="checkbox" value="' . $row['id'] . ' ?>"/></td>';
echo '<td>' . $row['title'] . '</td>';
echo '<td>' . $row['author'] . '</td>';
echo '<td>' . $row['date_published'] . '</td>';
echo '<td>
<a href="?del=' . $row['id'] . '">Delete</a> |
<a href="?edit=' . $row['id'] . '">Edit</a>
</td>';
echo '</tr>';
}
?>
</table>
and the ajax request: (also in page.php)
function load_data(query) {
$.ajax({
url: "",
method: "POST",
data: {query: query},
success: function (data) {
$('#result').html(data);
}
});
}
$('#search_query').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
} else {
load_data();
}
});
Basically, I have a search bar where the user can type anything and then the table where I'm showing the columns (taken from a database table) will change dynamically.
The code I have above is working fine but every time I type anything on the search bar, an exact copy of the page is being displayed (everything in my page gets displayed twice). Is there a way I can make the AJAX request return the table only and not the entire page? (without moving the entire code in a separate php file as I want to accomplish this in a single file)
I believe the problem is because I'm passing the data (which contains the whole page) to the #result div. I've tried looking for a solution and been tweaking my code for the last 3 hours or so but to no avail. I'm relatively new to these web technologies (God there are so many!) and I hope someone can help.
Check the solution posted here Ajax to PHP on the same page
Basically it suggest that you shouldn't echo rather than exit() your response. Otherwise, the remainder of the page is "loaded" again after the if(isset... is finished.