• Auto suggest text field

    Here, We are presenting a simple auto suggest input text field. Using Ajax, PHP, js and jquery, process of this code snippet follows steps given bellow.

    1.) Whenever a key press event on a text box occur, a function in JavaScript is called which uses ajax to send the input in the text box to the name_fetch.php

    2.) Then name_fetch.php receives a post request and check for any matches in the database.

    3.) Matched result is sent back to the JavaScript code, Ajax, and display that bellow text box .

    4.) Index.html :-This is the index file ,which there is input box and the result to be shown as shown in the image above

    5.) script.js :-This file holds the ajax code used to send and receive ajax requests to/from the server.

    6.) config.php :-this code contain database connection information.

    7.) name_fetch.php :-this code fetch name and send to script.

    Database:

    View Code MYSQL
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    CREATE TABLE `username` (
     
      `id` int(5) NOT NULL auto_increment,
     
      `name` varchar(30) default NULL,
     
      PRIMARY KEY  (`id`)
     
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=167 ;
     
    INSERT INTO `username` (`id`, `name`) VALUES
     
    (1, 'midhun'),
     
    (2, 'scriptime'),
     
    (3, 'ajax'),
     
    (4, 'php'),
     
    (5, 'auto'),
     
    (6, 'blablabla'),
     
    (7, 'how'),
     
    (8, 'john'),
     
    (9, 'sam'),
     
    (10, 'smith');

    Index.php:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html xmlns="http://www.w3.org/1999/xhtml">
     
    <head>
     
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     
    <title>Ajax php Auto Suggest </title>
     
    <link href="css/style.css" rel="stylesheet" type="text/css">
     
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
     
    <script language="JavaScript" src="js/script.js"></script>
     
    </head>
     
     <body>
     
     <center>
     
       <div class="main">
     
               <div id="holder">
     
                        Enter Keyword : <input type="text" id="keyword" tabindex="0"><img src="images/loading.gif" id="loading">
     
                        </div>
     
                        <div id="ajax_response"></div>
     
       </div>
     
     </center>
     
     </body>
     
    </html>

    style.css

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    
    body{
        font-family :Arial Black;
        font-size:12px;
    }
    body input{
        border: 1px solid #444A42;
        width: 200px;
        background : ;
    }
    body input:hover{
        border: 1px solid #0B0C0A;
        width: 200px;
        background : #FFFFFF;
    }
    .main{
        border : 0px solid #8789E7;
        background : ;
        padding: 10px 0px;
        width : 800px;
        height : 40px;
    }
    #loading{
        visibility:hidden;
        padding-left:5px;
    }
    #ajax_response{
        border : 1px solid #8789E7;
        background : #FFFFFF;
        position:absolute;
        display:none;
        padding:2px 2px;
        top:auto;
    }
    #holder{
        width : 350px;
    }
    .list {
        padding:0px 0px;
        margin:0px;
        list-style : none;
    }
    .list li a{
        text-align : left;
        padding:2px;
        cursor:pointer;
        display:block;
        text-decoration : none;
        color:#000000;
    }
    .selected{
        background : #CCCFF2;
    }
    .bold{
        font-weight:bold;
        color: #131E9F;
    }
    .about{
        text-align:right;
        font-size:10px;
        margin : 10px 4px;
    }
    .about a{
        color:#BCBCBC;
        text-decoration : none;
    }
    .about a:hover{
        color:#575757;
        cursor : default;
    }

    script.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    
    $(document).ready(function(){
     
              $(document).click(function(){
     
                       $("#ajax_response").fadeOut('slow');
     
              });
     
              $("#keyword").focus();
     
              var offset = $("#keyword").offset();
     
              var width = $("#keyword").width()-2;
     
              $("#ajax_response").css("left",offset.left);
     
              $("#ajax_response").css("width",width);
     
              $("#keyword").keyup(function(event){
     
                        //alert(event.keyCode);
     
                        var keyword = $("#keyword").val();
     
                        if(keyword.length)
     
                        {
     
                                  if(event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13)
     
                                  {
     
                                           $("#loading").css("visibility","visible");
     
                                           $.ajax({
     
                                             type: "POST",
     
                                             url: "name_fetch.php",
     
                                             data: "data="+keyword,
     
                                             success: function(msg){  
     
                                                    if(msg != 0)
     
                                                      $("#ajax_response").fadeIn("slow").html(msg);
     
                                                    else
     
                                                    {
     
                                                      $("#ajax_response").fadeIn("slow");     
     
                                                      $("#ajax_response").html('<div style="text-align:left;">No Matches Found</div>');
     
                                                    }
     
                                                    $("#loading").css("visibility","hidden");
     
                                             }
     
                                           });
     
                                  }
     
                                  else
     
                                  {
     
                                          switch (event.keyCode)
     
                                          {
     
                                           case 40:
     
                                           {
     
                                                      found = 0;
     
                                                      $("li").each(function(){
     
                                                               if($(this).attr("class") == "selected")
     
                                                                       found = 1;
     
                                                      });
     
                                                      if(found == 1)
     
                                                      {
     
                                                              var sel = $("li[class='selected']");
     
                                                              sel.next().addClass("selected");
     
                                                              sel.removeClass("selected");
     
                                                      }
     
                                                      else
     
                                                              $("li:first").addClass("selected");
     
                                                     }
     
                                           break;
     
                                           case 38:
     
                                           {
     
                                                      found = 0;
     
                                                      $("li").each(function(){
     
                                                               if($(this).attr("class") == "selected")
     
                                                                       found = 1;
     
                                                      });
     
                                                      if(found == 1)
     
                                                      {
     
                                                             var sel = $("li[class='selected']");
     
                                                              sel.prev().addClass("selected");
     
                                                              sel.removeClass("selected");
     
                                                      }
     
                                                      else
     
                                                              $("li:last").addClass("selected");
     
                                           }
     
                                           break;
     
                                           case 13:
     
                                                    $("#ajax_response").fadeOut("slow");
     
                                                    $("#keyword").val($("li[class='selected'] a").text());
     
                                           break;
     
                                          }
     
                                  }
     
                        }
     
                        else
     
                                 $("#ajax_response").fadeOut("slow");
     
              });
     
              $("#ajax_response").mouseover(function(){
     
                       $(this).find("li a:first-child").mouseover(function () {
     
                                   $(this).addClass("selected");
     
                       });
     
                       $(this).find("li a:first-child").mouseout(function () {
     
                                   $(this).removeClass("selected");
     
                       });
     
                       $(this).find("li a:first-child").click(function () {
     
                                   $("#keyword").val($(this).text());
     
                                   $("#ajax_response").fadeOut("slow");
     
                       });
     
              });
     
    });

    Config.php

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    <?php
     
    $host    = "localhost"; // Host name
     
    $db_name = "test1";          // Database name
     
    $db_user = "root";             // Database user name
     
    $db_pass = "";                            // Database Password
     
    $db_table= "username";               // Table name
     
    $db_column = "name";       // Table column from which suggestions will get shown
     
     
     
     $conn = mysql_connect($host,$db_user,$db_pass)or die(mysql_error());
     
     mysql_select_db($db_name,$conn)or die(mysql_error());
     
    ?>

    name_fetch.php

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    
    <?php
     
              include("config.php");
     
              $keyword = $_POST['data'];
     
              $sql = "select name from ".$db_table." where ".$db_column." like '".$keyword."%' limit 0,20";
     
              //$sql = "select name from ".$db_table."";
     
              $result = mysql_query($sql) or die(mysql_error());
     
              if(mysql_num_rows($result))
     
              {
     
                       echo '<ul class="list">';
     
                       while($row = mysql_fetch_array($result))
     
                       {
     
                                 $str = strtolower($row['name']);
     
                                 $start = strpos($str,$keyword);
     
                                 $end   = similar_text($str,$keyword);
     
                                 $last = substr($str,$end,strlen($str));
     
                                 $first = substr($str,$start,$end);
     
     
     
                                 $final = '<span class="bold">'.$first.'</span>'.$last;
     
     
     
                                 echo '<li><a href=\'javascript:void(0);\'>'.$final.'</a></li>';
     
                       }
     
                       echo "</ul>";
     
              }
     
              else
     
                       echo 0;
     
    ?>

Comments on this post

Leave a Reply

  • Security Code :


    three + 6 =