Fetch mysql data using ajax when one input is filled
Respected all users,
I am facing a little problem in using ajax+jQuery. I have two field in database
roll and
name . Now i have designed a html form containing two input type field
roll and
name . I want when i enter the existing roll in the roll field and enter tab or any other key the
name field should automatically filled with the related name stored in database.Thanks in advance
My codes are here
index.php
- <html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var searchTimeout; //Timer to wait a little before fetching the data
$("#roll").keyup(function() {
searchKey = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(searchKey);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers(searchKey) {
$.ajax({
url: 'getUser.php',
type: 'POST',
dataType: 'json',
data: {value: searchKey},
success: function(data) {
if(data.status) {
$("#name").val(data.userData.name);
} else {
// Some code to run when nothing is found
}
}
});
}
</script>
</head>
<table>
<tr>
<td>Roll</td>
<td><input type="text" name="roll" id="roll" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name" /></td>
</tr>
</table>
</html>
getUser.php
- <?php
include "db.php";
$response = Array();
$response['status'] = false;
$query = mysql_query("SELECT `name` FROM `tab` WHERE `roll` LIKE '%".$_POST['value']."%' LIMIT 1"); //Or you can use = instead of LIKE if you need a more strickt search
if(mysql_num_rows($query)) {
$userData = mysql_fetch_assoc($query);
$response['userData'] = $userData;
$response['status'] = true;
}
echo json_encode($response);
?>