Wednesday 5 March 2014

Autocomplete with PHP, MySQL and Jquery


Autocomplete with PHP, jQuery and MySQL Autocomplete Php is a cool technic you should learn to make your website or you web application looks cool and also user friendly. As you might have known, autocomplete gives a user a list of nearly same data with what he or she is looking for.





For this example there will be two files, autocomplete.php and search.php we have to creat table users like:
CREATE TABLE users
(
ID int,
name varchar(255)
); 
First autocomplete.php file with form and jquery js and css files.
Then when jQuery has been loaded add a trigger to the class auto adding autocomplete() I've set two options which are the source for the data in this case search.php and minLengh which determines how many letters must be used before a match is returned.

<html>
   <head>
        <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript"
  src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js "></script>
        <link rel="stylesheet" type="text/css"
    href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />

         <script type="text/javascript">
                $(document).ready(function(){
                    $("#name").autocomplete({
                        source:'search.php',
                        minLength:1
                    });
                });
        </script>
   </head>
 
   <body>
      <form method="post" action="">
             Name : <input type="text" id="name" name="name" />
      </form>
    </body>
</html>
search.php file contain DataBase connection details and sql query and return search details
<?php
 mysql_connect("localhost","root"," ");
 mysql_select_db("your db name");
 
 $term=$_GET["term"];
 
 $query=mysql_query("SELECT * FROM users where name like '%".$term."%'");
 $json=array();
 
    while($result=mysql_fetch_array($query)){
         $json[]=array(
                    'value'=> $result["name"]
                     );
    }
 
 echo json_encode($json);
 
?>

No comments:

Post a Comment