Translate

Monday 1 July 2013

Autocomplete Select Box Using Ajax,PHP,Mysql

Screenshot:
                          
index.php:

<html>
<head>
<title></title>
<link rel="stylesheet" href="autocomplete.css" type="text/css" media="screen">
<script src="jquery.js" type="text/javascript"></script>
<script src="dimensions.js" type="text/javascript"></script>
<script src="autocomplete.js" type="text/javascript"></script>

<script type="text/javascript">
    $(function(){
        setAutoComplete("searchField", "results", "action.php?part=");
    });
</script>
</head>

<body>
    <h1>Autocomplete Select Box using PHP,Ajax& MySQL</h1>
    <p id="auto">
        <label>Combinations: </label>
        <input id="searchField" name="searchField" type="text" />
    </p>    
    
</body>

</html>
        
action.php

<?php

$link = mysql_connect('localhost', 'root', '');
if (!$link) {
   die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db("search_box")) {
   echo "Unable to select mydbname: " . mysql_error();
   exit;
}

$result = mysql_query("SELECT name FROM  sks_color");
while ($row = mysql_fetch_assoc($result)) {
        $colors[]=$row['name'];
}
mysql_free_result($result);
mysql_close($link);

// check the parameter
if(isset($_GET['part']) and $_GET['part'] != '')
{
    // initialize the results array
    $results = array();

    // search colors
    foreach($colors as $color)
    {
        // if it starts with 'part' add to results
        if( strpos($color, $_GET['part']) === 0 ){
            $results[] = $color;
        }
    }

    // return the array as json with PHP 5.2
    echo json_encode($results);
}

Download:js


4 comments:

  1. hai,i am new to all these php and ajax...to get autocomplete search box i used this code as given .........but not working...

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. It will not work unless you create a CSS for it. The code executes fine but z-index has to be set to show the auto-complete result.

    ReplyDelete
  4. please post the autocomplete.css

    ReplyDelete