I have a Google Instant style search script written in jQuery which queries a PHP file. Currently, when no results are found, the PHP file returns no HTML code so the script displays a message saying “No results were found.”. However, when there are no search terms in the search box and the query string is empty this message is still displayed. How can I get it so that the message is only shown when there is text in the search box?
Here is my jQuery code:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&category=web';
window.location.hash='search/'+query+'/1/';
document.title=$(this).val()+" - My Search Script";
if(search==''){
window.location.hash='';
document.title='My Search Script';
}
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
if(response !=""){
$("#result").html(response);
} else {
$("#result").html("No results were found.");
}
}
});
});
});
The request is still firing even when there is nothing in the search field. Only make the request if the field isn’t empty.