Download AJAX chained select

Demo

PHP

This script requires PHP. You can also other server side languages if you rewrite the code for getCities.php(See below)

Put this into your <HEAD> section

Put this into your <BODY> section

Download Javascript file

I have used the Simple Ajax Code Kit library(SACK) for this script. I have made a copy available for download here.

Put ajax.js in a subfolder called "js" or change the path to the file in the code above(i.e. <script type="text/javascript" src="js/ajax.js"></script>)

Configuration

This script works like this:

  • Someone select a country from the select box. This triggers the function getCityList()
  • Ajax executes the file getCities.php to get a list of cities from the selected country
  • The script executes the response from Ajax, i.e. creates a list of cities in the second select box

getCities.php

Ajax sends a request to the file getCities.php which returns a list of cities. A server side script like this will usually return data from a database. However, I have in this demo used static data to make things simple.

Here's the content of getCities.php:

<?php

if(isset($_GET['countryCode'])){
  
  switch($_GET['countryCode']){
    
    case "no":
      echo "obj.options[obj.options.length] = new Option('Bergen','1');\n";
      echo "obj.options[obj.options.length] = new Option('Haugesund','2');\n";
      echo "obj.options[obj.options.length] = new Option('Oslo','3');\n";
      echo "obj.options[obj.options.length] = new Option('Stavanger','4');\n";
      
      break;
    case "dk":
      
      echo "obj.options[obj.options.length] = new Option('Aalborg','11');\n";
      echo "obj.options[obj.options.length] = new Option('Copenhagen','12');\n";
      echo "obj.options[obj.options.length] = new Option('Odense','13');\n";
      
      break;
    case "us":
      
      echo "obj.options[obj.options.length] = new Option('Atlanta','21');\n";
      echo "obj.options[obj.options.length] = new Option('Chicago','22');\n";
      echo "obj.options[obj.options.length] = new Option('Denver','23');\n";
      echo "obj.options[obj.options.length] = new Option('Los Angeles','24');\n";
      echo "obj.options[obj.options.length] = new Option('New York','25');\n";
      echo "obj.options[obj.options.length] = new Option('San Fransisco','26');\n";
      echo "obj.options[obj.options.length] = new Option('Seattle','27');\n";
      
      break;
  }  
}

?>

Copy the code and create the file getCities.php. Put it in the same folder as the main script


Tweet

Advertisement:
A logo design contest at Logomyway



About/Contact | A good idea? | Submit a script | Privacy notice
© 2005 - 2010 dhtmlgoodies.com