Wednesday, February 20, 2013

A jQuery AJAX example: giving a hint in input box



In this example, when users type firstname in the text box, the suggestion will be given at the same time.
In test1.php:
<?php
$array = array("apple","cake", "jiansen", "foo", "bar", "hallo", "world","test");
foreach($array as $v1)
{
    $ss=$_POST['suggest'];
    if(preg_match("/$ss/i", "$v1"))
       echo $v1.'<br />';
}
?>

Here we get $_POST['suggest'] from ajax in jquery, "/$ss/i" is case insensitive search using PHP function preg_match. $array is the hint array stored in server.
index.html: using ajax  $.post to post suggest to test1.php
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("input").keyup(function(){
    txt=$("input").val();
    $.post("test1.php",{suggest:txt},function(result){
      $("span").html(result);
    });
  });
});
</script>
</head>
<body>
<p>Start typing a name in the input field below:</p>
First name:
<input type="text" />
<p>Suggestions: <span></span></p>
</html>

Demo:

No comments:

Post a Comment