0

I need to cascade two drop down boxes using ajax. In my routine, 1st drop down is for country and second one is for state. while i select the country, the state's drop down displays those country's state. please help me in code. thanks in advance.

My Ajax function:

<script type="text/javascript">
function showstate(str)
{
if (str=="")
{
document.getElementById("fieldstate").innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("fieldstate").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","state_ajax.php?q="+str,true);
xmlhttp.send();
}
</script>

my HTML code:

        <select name="frmCountry" id="frmCountry" class="fiels" onchange="showstate(this.value)" onblur="checkEmpty('frmCountry', 'error_country', 'Please select the country');">
        <option value="">Please Select</option>
        <?php for($i=0;$i<count($strCountries);$i++) { ?>
            <option value="<?php echo $strCountries[$i]['coun_name']; ?>" <?php if($_POST['frmCountry']==$strCountries[$i]['coun_name']) { ?> selected="selected" <?php } ?>><?php echo ucfirst($strCountries[$i]['coun_name']); ?></option>
        <?php } ?>
        </select>

        <select name="frmState" id="frmState" class="fiels" onblur="checkEmpty('frmState', 'error_state', 'Please select the state');">
        <option value="">Please Select</option>
        </select>

state_ajax.php:

<?php
$q=$_GET["q"];

include("includes/config.php"); 

$strStates = doSelectCountryById('state_name', $q);

echo "<select>"
for($i=0;$i<count($strStates);$i++) {
echo "<option>" . $strStates[$i]['state_name'] . "</option>";
}
echo "</select>";
?>

The above code is for cascading two dropdown boxes using ajax, but the second dropdown cannot display, please help me in code. thanks in advance...

1
  • stackoverflow.com/help/mcve please deiscribe what happens, what should, what errors are produced, which lines are problematic, etc. "the second cannot display" is not sufficient. Dont forget to format and indent your code so it is readable. Commented Sep 3, 2014 at 7:37

1 Answer 1

1

Drop Down List in PHP Create file Index.php and Paste the following code :

<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('prem');
$query="SELECT * FROM country";
$result=mysql_query($query);
?>

<html>
<head>
<title>Country State City Dropdown Using Ajax</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
 var xmlhttp=false;          
try{
xmlhttp=new XMLHttpRequest();
}
catch(e){                             
                                                    try{                                        
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
                                                                                    xmlhttp=false;
}
}
}

return xmlhttp;
}

function getState(countryId) {                  

var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();

if (req) {

req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
                                                                                if (req.status == 200) {                                                                                  
                                                                                           document.getElementById('statediv').innerHTML=req.responseText;
                                                                                           document.getElementById('citydiv').innerHTML='<select name="city">'+
                                                                                           '<option>Select City</option>'+
                                                                        '</select>';                                                                                
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
                                                                }                                                             
                                                }                                             
req.open("GET", strURL, true);
req.send(null);
}                             
}
function getCity(countryId,stateId) {                     
var strURL="findCity.php?country="+countryId+"&state="+stateId;
var req = getXMLHTTP();

if (req) {

req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {                                                                                  
                                                                                                document.getElementById('citydiv').innerHTML=req.responseText;                                                                                      
} else {
                                                                                           alert("Problem while using XMLHTTP:\n" + req.statusText);
                                                                                }
}                                                             
                                                }                                             
req.open("GET", strURL, true);
req.send(null);
}

}
</script>

<style type="text/css">
body {font-family: Arial, "Trebuchet MS";font-size: 17px;color: #52B6EB; }
a{font-weight: bold;letter-spacing: -1px;color: #52B6EB;text-decoration:none;}
a:hover{color: #99A607;text-decoration:underline;}
#top{width:43%;margin-top: 25px; height:60px; border:1px solid #BBBBBB; padding:10px;}
#tutorialHead{width:43%;margin-top: 12px; height:30px; border:1px solid #BBBBBB; padding:11px;}
.tutorialTitle{width:95%;float:left;color:#99A607}
.tutorialTitle  a{float:right;margin-left:20px;}
.tutorialLink{float:right;}
table
{
margin-top:70px;
border: 1px solid #BBBBBB;
padding:25px;
height: 35px;
}
</style>
</head>
<body>
<form method="post" action="insert.php" name="form1">
<center>
<div id='top'>
         <a href="http://www.technaitra.com" title="Technaitra Solutions" target="blank">
             <img src="image/mainlogo.png" alt="Technaitra Solutions" title="Technaitra Solutions" border="0"/>
         </a>
</div>

    <div id='tutorialHead'>
         <div class="tutorialTitle"><b>Country State City Dropdown Using Ajax</b>
          <a href="http://phpwithsmile.blogspot.in" title="Country State City Dropdown Using Ajax">Tutorial Link</a>
    </div>
</div>


<table width="45%"  cellspacing="0" cellpadding="0">
  <tr>
    <td width="75">Country</td>
     <td width="50">:</td>
    <td  width="150"><select name="country" onChange="getState(this.value)">
                <option value="">Select Country</option>
                <?php while ($row=mysql_fetch_array($result)) { ?>
                <option value=<?php echo $row['id']?>><?php echo $row['country']?></option>
                <?php } ?>
                </select></td>
  </tr>
  <tr style="">
    <td>State</td>
    <td width="50">:</td>
    <td ><div id="statediv"><select name="state" >
                <option>Select State</option>
        </select></div></td>
  </tr>
  <tr style="">
    <td>City</td>
    <td width="50">:</td>
    <td ><div id="citydiv"><select name="city">
                <option>Select City</option>
        </select></div></td>
  </tr>

</table>
</center>

<input name="Submit" type="Submit" value="Submit">

</form>
</body>
</html>

Create file findstate.php and Paste the following code :

<?php
error_reporting(0);

$country=intval($_GET['country']);
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('prem');
$query="SELECT id,statename FROM state WHERE countryid='$country'";
$result=mysql_query($query);

?>
<select name="state" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select State</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['id']?>><?php echo $row['statename']?></option>
<?php } ?>
</select>

Create file findcity.php and Paste the following code :

<?php
error_reporting(0);

$countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('prem');
$query="SELECT id,city FROM city WHERE countryid='$countryId' AND stateid='$stateId'";
$result=mysql_query($query);

?>
<select name="city">
<option>Select City</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['id']?>><?php echo $row['city']?></option>
<?php } ?>
</select>

Create file insert.php and Paste the following code :

<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?php
error_reporting(0);

$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("prem", $con);

$sql="INSERT INTO result (country,state,city)
VALUES
('$_POST[country]','$_POST[state]','$_POST[city]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con);
?>

</body>
</html>

Database File: Create Database with name prem and paste the following in SQL : /* Create table country */

CREATE TABLE `country` (
  `id` tinyint(4) NOT NULL auto_increment,
  `country` varchar(20) NOT NULL default '',
  PRIMARY KEY  (`id`)
)

/create table state/

CREATE TABLE `state` (
  `id` tinyint(4) NOT NULL auto_increment,
  `countryid` tinyint(4) NOT NULL,
  `statename` varchar(40) NOT NULL,
  PRIMARY KEY  (`id`)
)

/* Create table city */

CREATE TABLE `city` (
  `id` tinyint(4) NOT NULL auto_increment,
  `city` varchar(50) default NULL,
  `stateid` tinyint(4) default NULL,
  `countryid` tinyint(4) NOT NULL,
  PRIMARY KEY  (`id`)
)

/* Insert records into country table */

INSERT INTO `country` VALUES (1, 'USA');
INSERT INTO `country` VALUES (2, 'Canada');

/* Insert records into state table */

INSERT INTO `state` VALUES (1, 1, 'New York');
INSERT INTO `state` VALUES (2, 1, 'Los Angeles');
INSERT INTO `state` VALUES (3, 2, 'British Columbia');
INSERT INTO `state` VALUES (4, 2, 'Toranto');

/* Insert records into city table */

INSERT INTO `city` VALUES (1, 'Los Angales', 2, 1);
INSERT INTO `city` VALUES (2, 'New York', 1, 1);
INSERT INTO `city` VALUES (3, 'Toranto', 4, 2);
INSERT INTO `city` VALUES (4, 'Vancovour', 3, 2);

/* Create table Result*/

CREATE TABLE `result` (
  `id` tinyint(4) NOT NULL auto_increment,
  `city` varchar(50) default NULL,
   `state` varchar(50) default NULL,
 `country` varchar(50) default NULL,
  PRIMARY KEY  (`id`)
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.