I am trying to generate suggestions using data in a database without refreshing the page as a user types some data in the input field below. AJAX is quite new to me and I have been trying to figure out where I went wrong for quite some time now. It seems as if the code below is not returning any results at all. I appreciate any help.
My markup:
<head>
<title>Test</title>
<script type="text/javascript">
function search(searchword) {
$('#suggestion').load('invoice-get-data.php?searchword=' + searchword);
}
</script>
</head>
<body>
<div class="prod-name">
<!-- As user input data, call search function, and narrow down results on every keystore -->
<input onKeyPress="search(this.value)" type="text" id="prod-name"/>
<div id="suggestion"></div>
</div>
</body>
AJAX so far:
<?php
$conn = mysql_connect('localhost', 'root', 'mypassword');
if(!$conn){
die('Error: Unable to connect.' . '<br>' . mysql_error());
}
mysql_select_db("mydb", $conn);
$searchword = $_GET['searchword'];
$results = mysql_query("SELECT * FROM products WHERE prod-name LIKE '$searchword'") or die(mysql_error());
while($row = mysql_fetch_array($results)){
echo $row['prod-name'] . '<br/>';
}
?>
for starters, the “onchange” event doesn’t fire until a textbox has lost focus (meaning the cursor goes out of the textbox). You are probably looking for a keyboard event like onkeyup or onkeypress.