AJAX: Refresh Country List upon typing

This example shows a list with countries which is refined each time we narrow down the search by typing in more letters.

We need a table called “countries” with 2 fields:

  • “country” (e.g. Greece) and
  • “iso2” (e.g. GR)

We also need the following 3 files:

connection.php:

It is used by both files.

    $link=@mysql_connect("localhost","nista","nista123");
    if(!$link){
        die("Couln't open database!");
    }
    $db="examples";
    mysql_select_db($db) or die("Could not open the database");
?>

search_countries.php:

The main page, which contains the list and the javascript code which calls the livesearch_cities.php.







print "";
print "";
print "";
print "";
print "";
print "
Country:print "id='search_countries' value='' onkeyup='javascript:showCountries(this.value);'>";
print "
";
print "
print "style='visibility:hidden;'>
";
print "
";
print "
";
?>
   


livesearch_countries.php:

This fetches from the database the result and returns to search_countries.php in via javascript, in order to populate the div “livesearch_countries”.

header("Content-type: text/html; charset=utf-8");
//get the q parameter from URL
$q=$_GET["q"];
include("connection.php");
if (strlen($q)>0){
$hint="";
    $theQuery="SELECT c.country, c.iso2 ".
                "FROM countries c ".
                "where c.iso2<>'--' ".
                "and c.country like '".$q."%' LIMIT 11";
    $result=mysql_query("SET NAMES 'utf8'");
    $result=mysql_query($theQuery);
    $num_rows=mysql_num_rows($result);
    $x=0;
    $yellowEffect="OnMouseOut=\"this.style.backgroundColor='lightyellow';\" ".
    "OnMouseOver=\"this.style.backgroundColor='yellow';\"";
    while($a_row=mysql_fetch_row($result)){
        if($x<10){
            $hint=$hint."            stripslashes($a_row[1])."','".stripslashes($a_row[0])."-".
            stripslashes($a_row[1])."');\"  style='text-decoration:none;'>".
            stripslashes($a_row[0]).", ".stripslashes($a_row[1])."

";
        }
        else{
            $hint=$hint."
".
            "(More than 10 results)
";
        }
        $x++;       
    }
}

if ($hint==""){
    $response="
no results
";
}
else
  {
  $response=$hint;
  }

//output the response
echo $response; 
?>

wait.gif


Table countries:

CREATE TABLE `countries` (
  `CountryId` smallint(6) NOT NULL AUTO_INCREMENT,
  `Country` varchar(50) NOT NULL,
  `ISO2` varchar(2) NOT NULL,
  PRIMARY KEY (`CountryId`),
  KEY `iso2_idx` (`ISO2`)
) ENGINE=MyISAM AUTO_INCREMENT=276 DEFAULT CHARSET=latin1;
INSERT INTO `countries` (`CountryId`,`Country`,`ISO2`) VALUES 
 (95,'Greece','GR');

Leave a Reply