Skip to main content

AutoSuggest Using Jquery/Ajax ,PHP, MYSQL


Simple Text-field is normal. Lets try something new so now we'll dissuss about autoSuggest text-field. You can use it your Registration Form or as per you need. Its very classy. All Thanks goes to jquery. You need a database from where suggestions are displayed on client machine. For this purpose you need to create a database and upload the .sql file which is in the Zip folder.Include jquery scripts in head section of html.

Steps are simple just create a php file and use its code in html file.

Download

Requirements:

  1. HTML
  2. Jquery
  3. Ajax
  4. MYSQL
  5. PHP
In the PHP code which is saved in rpc.php lookup( ) takes the word from the input box and POST it to the rpc.php page using Jquery and Ajax  POST call.
If input string contains '0' it hides the suggestion box otherwise displays suggestions as per in the database.
We take the input string and post it to the php page using $.POST( )
<input id="inputString" onkeyup="lookup(this.value);" type="text" />
 
The 'callback' part allow to hook in the function. If the data returnefd length is more than '0' the it shows the suggestion box and replace the the data with HTML. This is really tricky.

PHP Code:

    
    // PHP5 Implementation - uses MySQLi.
    // mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
    $db = new mysqli('localhost', 'root' ,'', 'autocomplete');
    
    if(!$db) {
        // Show error if we cannot connect.
        echo 'ERROR: Could not connect to the database.';
    } else {
        // Is there a posted query string?
        if(isset($_POST['queryString'])) {
            $queryString = $db->real_escape_string($_POST['queryString']);
            
            // Is the string length greater than 0?
            
            if(strlen($queryString) >0) {
                // Run the query: We use LIKE '$queryString%'
                // The percentage sign is a wild-card, in my example of countries it works like this...
                // $queryString = 'Uni';
                // Returned data = 'United States, United Kindom';
                
                // YOU NEED TO ALTER THE QUERY TO MATCH YOUR DATABASE.
                // eg: SELECT yourColumnName FROM yourTable WHERE yourColumnName LIKE '$queryString%' LIMIT 10
                
                $query = $db->query("SELECT value FROM countries WHERE value LIKE '$queryString%' LIMIT 10");
                if($query) {
                    // While there are results loop through them - fetching an Object (i like PHP5 btw!).
                    while ($result = $query ->fetch_object()) {
                        // Format the results, im using
  • for the list, you can change it.                         // The onClick function fills the textbox with the result.                                                 // YOU MUST CHANGE: $result->value to $result->your_colum                          echo '
  • '.$result->value.'
  • ';                      }                 } else {                     echo 'ERROR: There was a problem with the query.';                 }             } else {                 // Dont do anything.             } // There is a queryString.         } else {             echo 'There should be no direct access to this script!';         }     } ?>
    The above php code is simple you can easily get it with the help of its comments inside the coding.  

    Javascript:

    Jaascript is too simple in the whole code just a function which is been called in the text filed where input is to be placed.

    function lookup(inputString) {
            if(inputString.length == 0) {
                // Hide the suggestion box.
                $('#suggestions').hide();
            } else {
                $.post("rpc.php", {queryString: ""+inputString+""}, function(data){
                    if(data.length >0) {
                        $('#suggestions').show();
                        $('#autoSuggestionsList').html(data);
                    }
                });
            }
        } // lookup
        
        function fill(thisValue) {
            $('#inputString').val(thisValue);
            setTimeout("$('#suggestions').hide();", 200);
        }

    HTML Code:

     

    <body>
     <div>
      <form>
       
        <h2>Type your county:</h2>
        <input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
       
       
       <div class="suggestionsBox" id="suggestions" style="display: none;">
        <img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
        <div class="suggestionList" id="autoSuggestionsList">
          
        </div>
       </div>
      </form>
     </div>
    </body>
     
    Hope you will like my post.

    Comments

    1. Hi, here's a good tutorial that may help you too, its a simple search that uses php and ajax to fetch data in mysql and display it quickly. http://www.upgradedtutorials.info/tutorials/fast-search-and-sorting-data-in-mysql-using-php-and-ajax/

      ReplyDelete

    Post a Comment

    your Comment is sent for moderation, Thankyou

    Popular posts from this blog

    Network Topologies (Tutorial-4)

    Topology refers to the way in which the network of computers is connected. The choice of topology is dependent upon--- Type and number of equipment being used  Planned applications and rate of data transfers  Required response times  Cost Types of Network Topologies Physical Topology: Physical topology defines how devices are connected to the network through the actual cables that transmit data(physical structure of the network)  Logical Topology: Logical Topology (also referred to as Signal Topology) is a network computing term used to describe the arrangement of devices on a network and how they communicate with one another.

    Cisco Hierarchical Model

    Cisco Hierarchical Model Defined by Cisco to simplify the design, implementation, and maintenance of responsive, scalable, reliable, and cost-effective networks. The 3 layers are logical and not physical – there may be many devices in a single layer, or a single device may perform the functions of 2 layers, eg: core and distribution. The Cisco Hierarchical Model

    Windows 7 transformation pack for xp

    As the windows 7 launched after that there are lot of screenshot available on the internet, There developer designed the transformation packs for xp to make it better lo0king like windows 7. There are some transformation packs for your xp. Download Vienna 2.5 – Windows 7 Transformation Pack (Mirror) Downloa d HFN Windows 7 Transformation Pack Download Windows 7 Transformation pack – NSFormation (Mirror) Download Vienna Transformation Pack v1