Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose we have two dropdown
dropdown1 for country and dropdown2 for state

i want to show the states in dropdown2 on dropdown1 change event(Ex:If i click india , It should load states of india with ajax)?

I just need example[edit] source code including php,html,ajax.

Thank you
Posted
Updated 12-Dec-13 0:46am
v2

You'll need to find the data somewhere... that's your job.
Try starting here.

Then you connect to your data and use onchange event.
 
Share this answer
 
v4
Hi Friend,

Here's an Example... A Complete Test Page with this feature
File: index.html

HTML
<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <title>Representation of AJAX</title>
 <script type="text/javascript">
   function update(str)
   {
      var xmlhttp;

      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("data").innerHTML = xmlhttp.responseText;
        }
      }

      xmlhttp.open("GET","demo.php?opt="+str, true);
      xmlhttp.send();
  }
</script>

</head>
<body>
  <select id="optionA" onchange="update(this.value)">
    <option value="0">Select...</option>
    <option value="1">Option1</option>
    <option value="2">Option2</option>
  </select>
  <br/>
  <select id="data">
    <option>Select an Option...</option>
  </select>
</body>
</html>


File: demo.php 

PHP
<?php
  $opt = $_GET['opt'];

  switch($opt)
  {
    case 0:
    default:
      echo '
            <option>Select an Option...</option>
           ';
        break;
    case 1:
      echo '
            <option value="opt1_1">Option1_Test1</option>
            <option value="opt1_2">Option1_Test2</option>
            <option value="opt1_3">Option1_Test3</option>
           ';
        break;
    case 2:
      echo '
            <option value="opt2_1">Option2_Test1</option>
            <option value="opt2_2">Option2_Test2</option>
            <option value="opt2_3">Option2_Test3</option>
           ';
        break;
  }
?>

Hope that this example will help.

With Regards
Tushar Srivastava
 
Share this answer
 
Comments
Mr.Venus 20-Dec-13 1:01am    


I need to call php arrays using ajax. I dont know how to do that.
Let us assume I am having three select box.In first Select Box If I click "india",Indian States should load in second select box.If I click any states from second select box, Corresponding cities should load in third select box.Thanks for the above code.Switch Statement is now clear.But I need array example to call ajax.Thank u
Er. Tushar Srivastava 21-Dec-13 22:55pm    
Alright I will be posting an example using arrays. Actually that is simple.
Hi again,
Here's an example using arrays.

PHP
    // We are defining a main array which is an enumerated array enumerated based on ISD codes of countries. Each index has
    // another array which contains states. If you want, You can have another array internal to it as one example given (not all)
    // to define cities in a state
    $array_main = array(
                    91 => array("Andra Pradesh" => array("Hyderabad","Vishakhapatnam","Tirupati"),
                            "Assam" => array(),"New Delhi" => array(),"Punjab" => array(),
                            "Haryana" => array(),"Tamil Nadu" => array(),"Kerala" => array(),"Utter Pradesh" => array()),
                    1 => array("California" => array(),"Texas" => array(),"Alaska" => array(),
                            "Massachusetts" => array(),"Virginia" => array(),"Colorado" => array()),
                    61 => array("South New Wales" => array(), "Victoria" => array(),
                            "Queensland" => array(), "Tasmania" => array())
                  );

    $country_code = $_GET['countryCode'];
    $state = $_GET['stateName'];

    // Now, we have two methods here,
    // First is to echo the contents and use the javascript in the frontend to use innerHTML to display it inside a selection box.
    // This feature has more edge. As more complex coding is at php side (not complex at all)
    // Another method is to pack the array in a json object (there's a function in php json_encode(array)) and then echo the array itself
    // Then you have to use javascript at the frontend to use the json object to extract and display the data. That completely depends 
    // on you.


    // We will use first method here. Now we will be testing few things to generate the required html
    if(!$country_code) return false;
    else {
        // Get the current country code and get the array associated with it.
        $array_state = $array_main[$country_code];
        if(!$state) {
            foreach ($array_state as $key=>$value) { // Since we possibly have another array inside it as cities
                echo '
                     <option value="'.$key.'">'.$key.'</option>';
                     ';
            }
            return true;
        }
        else {
            // Store the Cities also as array
            $array_cities = $array_main[$country_code][$state];

            foreach ($array_cities as $value) { // Now we don't have any further nesting
                echo '
                     <option value="'.$value.'">'.$value.'</option>';
                     ';
            }
            return true;
        }
    }
?>


The Front end will be changed and will use some kind of method that I am suggesting here.
JavaScript
$(document).ready(function(){
    $('#selectbox_country').change(function(){
        // We will create a querystring setting state and city blank
        queryString = '?countryCode=' + encodeURIComponent($(this).val()) + '&stateName=';

        // Now we will load the states in the next select box.
        $('#selectbox_state').load('http://www.example.com/script.php' + queryString);
    });

    $('#selectbox_state').change(function(){
        // We will create a querystring setting state and city blank
        queryString = '?countryCode=' + encodeURIComponent($('#selectbox_country').val()) + '&stateName='
                        + encodeURIComponent($(this).val());

        // Now we will load the states in the next select box.
        $('#selectbox_cities').load('http://www.example.com/script.php' + queryString);
    });

    $('#selectbox_cities').change(function(){
        // You can perform some other function here...

    });
});


I hope this example will help you understand the concept. Example though wasn't a well written code. But, you get the idea right.
You can have a look at a similar code of mine on my test website here

Open the source code of given link and read from line 205 ahead. That's a more advanced jQuery implementation of a similar concept.
You are free to copy and modify the code according to your need if you wish to...

With Regards
Tushar Srivastava
 
Share this answer
 
Comments
Mr.Venus 24-Dec-13 1:00am    
Thanks a lot brother. Now I am clear with your arrray concept.Though I dont know how to call php(arrays) by using ajax . Can pleae provide sample demo files of html,ajax,php for this scenerio individually..

<script type="text/javascript">
function update()
{
var xmlhttp;

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)

After this What I need to give? :( I was confused. kindly give me files individually
Er. Tushar Srivastava 25-Dec-13 6:11am    
Alright, :) Actually you have to use json for that.... Plase have a look at this link :) http://stackoverflow.com/questions/7313173/ajax-post-json-and-php-how-do-i-do-it This will help you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900