I have this file named ajax.php '
<?php
class AJAX {
private $database = NULL;
private $_query = NULL;
private $_fields = array();
public $_index = NULL;
const DB_HOST = "localhost";
const DB_USER = "root";
const DB_PASSWORD = "";
const DB_NAME = "dd";
public function __construct(){
$this->db_connect(); // Initiate Database connection
$this->process_data();
}
/*
* Connect to database
*/
private function db_connect(){
$this->database = mysql_connect(self::DB_HOST,self::DB_USER,self::DB_PASSWORD);
if($this->database){
$db = mysql_select_db(self::DB_NAME,$this->database);
} else {
echo mysql_error();die;
}
}
private function process_data(){
$this->_index = ($_REQUEST['index'])?$_REQUEST['index']:NULL;
$id = ($_REQUEST['id'])?$_REQUEST['id']:NULL;
switch($this->_index){
case 'country':
$this->_query = "SELECT * FROM country GROUP BY Name";
$this->_fields = array('Code','Name');
break;
case 'state':
$this->_query = "SELECT * FROM city WHERE CountryCode=$id";
$this->_fields = array('CountryCode','District');
break;
case 'city':
$this->_query = "SELECT * FROM city WHERE CountryCode=$id";
$this->_fields = array('CountryCode','Name');
break;
default:
break;
}
$this->show_result();
}
public function show_result(){
echo '<option value="">Select '.$this->_index.'</option>';
$query = @mysql_query($this->_query);
while($result = @mysql_fetch_array($query)){
$entity_id = $result[$this->_fields[0]];
$enity_name = $result[$this->_fields[1]];
echo "<option value='$entity_id'>$enity_name</option>";
}
}
}
$obj = new AJAX;
?>
and index.html with this js script
and form
<form>
<label>Select Country</label>
<select id="country" onchange="load_options(this.value,'state');">
<option value="">Select country</option>
</select>
<label>Select State</label>
<select id="state" onchange="load_options(this.value,'city');">
<option value="">Select state</option>
</select>
<label>Select city</label>
<select id="city">
<option value="">Select City</option>
</select>
<img src="loader.gif" id="loading" align="absmiddle" style="display:none;"/>
</form>
Country options are visible but when i want to choose the state it is not
Also i have two tables country and city and in the table city are included the districtsnames
You should use jQuery for easier to implement ajax callback. You can cache you data at client computer if it is not change frequently.
You can refer this topic jQuery set selected value in option box once the box has been loaded