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.

<html>
<head>
<script type="text/javascript">
function showCountries(str)
{
document.getElementById("wait_countries").style.visibility="visible";
if (str.length==0)
  {
  document.getElementById("livesearch_countries").innerHTML="";
  document.getElementById("livesearch_countries").style.border="0px";
  document.getElementById("livesearch_countries").style.visibility="hidden";
  document.getElementById("wait_countries").style.visibility="hidden"; 
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch_countries").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch_countries").style.border="1px solid #A5ACB2";
    document.getElementById("livesearch_countries").style.visibility="visible";
    document.getElementById("wait_countries").style.visibility="hidden";   
    }
  }
xmlhttp.open("GET","livesearch_countries.php?q="+str,true);
xmlhttp.send();
}

//----------------
function saveCountry(countryId, countryDesc){
    alert("selected: " + countryDesc);
}
</script>
</head>
<body>
<FORM>
<?
print "<table border=0>";
print "<tr style='font-size: 12;color:grey;'>";
print "<td><b>Country:</b><input type='text' class='searchField' name='search_countries' ";
print "id='search_countries' value='' onkeyup='javascript:showCountries(this.value);'>";
print "<div id='livesearch_countries' class='searchList'></div>";
print "</td>";
print "<td><img id='wait_countries' src='./images/icons/wait.gif' ";
print "style='visibility:hidden;'></td>";
print "</tr>";
print "</table>";
print "<br/>";
print "</div>";
?>
</FORM>   
</body>
</html>

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."<a ".$yellowEffect." href=\"javascript:saveCountry('".
            stripslashes($a_row[1])."','".stripslashes($a_row[0])."-".
            stripslashes($a_row[1])."');\"  style='text-decoration:none;'>".
            stripslashes($a_row[0]).", ".stripslashes($a_row[1])."</a><br/>";
        }
        else{
            $hint=$hint."<div style='background-color:darkblue;color:white;font-weight:bold;'>".
            "(More than 10 results)</div>";
        }
        $x++;       
    }
}

if ($hint==""){
    $response="<div style='background-color:darkblue;color:white;font-weight:bold;'>no results</div>";
}
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