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

    Eden: PHP Library To Get Things Easy For PHP Developer

    Eden is PHP Library designed for helping developers in their rapid development work. In Our most of the project we have to integrate our developed website or application with most of  the social networking websites like Google, Facebook, Twitter, yahoo etc. so what we do is we integrate libraries of different websites differently Although We could make the code reusable but still if the websites increases then confusion will also increases. Adding different libraries form different sources add more complexity to your project and ends up to be hard to maintain. Eden simply a set of reusable components, that works with any PHP framework and CMS. Eden makes code logical and readable with dead simple syntax. Eden Will work With Most Of Web services including Amazon Web service Facebook Foursquare Google twitter tumbler Paypal Yahoo You could Download the File From  Eden Official Website  and Can use this will just a simply including this...