This is my index.php file
$(document).ready(function(){
$('#search').keyup(function(){
var txt = $(this).val();
if(txt.length != ''){
$.ajax({
url:"php/search.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data){
$('#result').html(data);
}
});
} else {
$('#result').html('');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 align="center">This is a sample of web application using sql server database and php manager in IIS</h3>
<br>
<input type="text" name="search" id="search" placeholder="Search keywords" autocomplete="off"/>
<br><br>
<div id="result"></div>
How to make sure that default table (eg: SELECT * FROM pclisting) can be viewed first before the searching takes place. In other word, how to show the data in 'pclisting' table in the same div (#result) when the user has not typed in anything in the search text box?
Right now I can only view all the data if the keywords has been typed in. Otherwise it will show an empty #result div.
</div>
If I understand correctly you want to show all results when the page is first loaded up, then filter with keystroke content when the user is typing.
To do this, you need to have a condition in search.php that when the value of the 'search' parameter passed to it is null (or empty string, or whatever you choose), it returns all results. Then you need to run your ajax script on page load initially.
You should separate your ajax method out into a separate function that can be called outside of your keystroke event handler. This way you can call it in the initial load to return all your results, and call it again with the keystroke value from your listener. Something like this:
function getResults(txt='') {
$.ajax({
url:"php/search.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data) {
$('#result').html(data);
}
});
}
$(document).ready(function(){
$('#search').keyup(
getResults($(this).val());
);
getResults(); // Call this intially with no value
});
In your PHP change:
$sql = "SELECT * FROM pclisting WHERE device_id LIKE '%$search%' OR section LIKE '%$search%'";
to:
if (empty($_POST["search"])) {
$sql = "SELECT * FROM pclisting";
} else {
$sql = "SELECT * FROM pclisting WHERE device_id LIKE '%$search%' OR section LIKE '%$search%'";
}
Also you should really consider sanitizing the value of $search before you use it in your mysql statement.