I have a simple search area that that uses JavaScript to display relevant search results while the user is typing. The following is the code for it:
<div class="message_content">
<input type="text" id="user_search" class="form-control search_box" placeholder="Search for people">
<div id="search_results">
<span class="no-result" style="line-height: 38px;">Enter your query</span>
</div>
</div>
The following is the JS in lib.js
:
$("input#user_search").keyup(function() {
var elt = $("input#user_search").val();
$curr = $(this);
$.ajax({
url : "u.search.php",
type: "GET",
data : {val: elt},
success:function(data, textStatus, jqXHR)
{
if (data.length) {
$("div#search_results").html(data);
}
else $("div#search_results").html('<span class=\"no-result\">Enter your query</span>');
},
error: function(jqXHR, textStatus, errorThrown){}
});
});
Lastly, the following is the code for u.search.php
:
<?php
$search = strtolower(htmlspecialchars($_GET['val']));
if (strlen($search) < 1);else {
// Run query on the DB
...
print "<div id=\"search-list\" class=\"list-group\">";
// populate results
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
// variable declarations
print "<a href=\"#\" id=\"$result\" class=\"list-group-item\">";
print "<img src=\"$pic\">";
print "<span>$name</span>";
print "</a>";
}
print "</div>";
}
?>
The problem here is that if I type anything in the textbox, the index.php
page (page where the search box resides), the html of div#search_results
becomes index.php
. If I do console.log(data)
in the ajax success
function, the console shows the code of the index.php page (not the actual source code, but the one that you can see in the browser's page source).
div#search_results
basically has index.php embedded inside it. I tried making changes to the PHP backend code, but no changes reflected in the results. What's wrong here?
You are using the Querystring to get the search variable. But you are not sending anything. So change your search.php to use POST or change the ajax method to send the query string...
$.ajax({
url : "u.search.php?val=" + encodeURIComponent(elt),
type: "GET",
success:function(data, textStatus, jqXHR)
{
if (data.length) {
$("div#search_results").html(data);
}
else $("div#search_results").html('<span class=\"no-result\">Enter your query</span>');
},
error: function(jqXHR, textStatus, errorThrown){}
});