I am trying to create an html form that uses AJAX to load database entries from a mysql database as the user types, so it suggests them to the user.
I am new to AJAX and I am kind of stuck with something that probably is quite simple for more experienced people.
I have this html text input:
<form>
<input type="text" id="f" />
</form>
This jQuery script:
$(function(){
ajaxTest();
})
function ajaxTest(){
$('#f').keyup(function(){
$.ajax({
url: 'getit.php',
dataType: 'json',
data: {'data' : this.value},
success: function(response){
for(var i = 0; i < (response.rows*2); i = i+2){
alert('The name is ' + response[i] + ' ' + response[i+1])
}
}
})
})
}
And this php script:
//connect to database
//get variables an sanitize
$parameter = $_GET['data'];
$parameter = mysql_real_escape_string( $parameter );
//prepare and run query
$query = "SELECT email , surname , address FROM users WHERE email LIKE '$parameter%'";
$result = mysql_query($query);
//start preparing response
$seires = mysql_num_rows($result);
$response = array('rows'=>$seires);
while($row = mysql_fetch_array( $result ) ) {
array_push( &$response , $row['onoma'] , $row['epwnimo'] );
}
echo json_encode($response);
This gets my job done, but I am wondering:
1) Am I using any bad practices?
2) Is there a smarter way to pass the data from the php script to the jQuery script?
3) In html, what tag could I use to display the suggestions to the user? A p with an onclick function to fill the form perhaps or is there something better?
I would be worried about making too many ajax calls. It is likely that someone will be typing fast. So if I type ‘abc’ then you will make 3 ajax calls. Lots of overhead. However, if you to implement a delay before sending like 300 milliseconds then the script will wait for a pause before returning results.
I find that a short (really unnoticeable) delay is better than a flicker in the suggestions.
Also, you might consider posting this on codereview (stackoverflow’s companion site). It is better suited for answer questions like this one.
Here is an untested example of what I am referring to: