Friday 8 July 2016

Ajax dependent dropdown (Country, State, City) without DATABASE


Ajax dropdown dependent script. Sometimes we need to develop some good User interface without page reload, then jQuery AJAX comes to rescue.

This is a basic script which use jQuery ajax and some PHP code to process the request.

I develop this without any database connection. For the Country, State, City values I've created some sort of arrays (two-dimentional/multi-dimentional as well).

Dependent dropdown is used in various way, We are going to check how it works with Country, State, City.
When you select country dropdown based on that it will show state dropdown below dynamically.

For that we use on change event, when you change value in country dropdown, an AJAX request fires to external PHP files and shows the results.
Which results in dynamic states in dropdown for that selected country and so on.

We can use database for country, state and city values instead of static arrays.


1. Create a file with a name, for example "ajax_dependent.php" and copy below code in it.
<!DOCTYPE html>
<html>
<head>
    <title>Ajax dependent dropdown (Country, State, City)</title>
    <script type="text/javascript" src="jquery.js"></script>
</head>
<style type="text/css">
    body{font-family: arial;font-size: 14px;}
    .form_container{border: 1px dashed #ccc;float: left;}
    form{width: 400px;padding: 5px;}
    div.input_row{width: 100%;float: left;margin: 5px 0;}
    .input_row label{width: 30%;float: left;}
    .input_row .input_fields{float: left;width: 70%;}
    select{width: 100%;}
</style>
<body>
<script>
    $(document).ready(function(){
        /*script run when you select country from dropdown*/
        $(document).on("change",".select_country",function(){ // You can either use $(".select_country").change(function(){ 
            var country = $(this).val();
            $.ajax({
                type: "POST",
                data: "country="+country,
                url: "process.php",
                success: function(data) {
                    if(data!="") {                
                        $(".select_state").html(data);
                        $(".select_city").html('<option value="">-- Select State --</option>');
                    }else{
                        alert("there's some problem");
                    }
                }
            });
        });
        /*script run when you select state from dropdown*/
        $(document).on("change",".select_state",function(){
            var state = $(this).val();
            $.ajax({
                type: "POST",
                data: "state="+state,
                url: "process.php",
                success: function(data) {
                    if(data!="") {                
                        $(".select_city").html(data);
                    }else{
                        alert("there's some problem");
                    }
                }
            });
        });
    });
</script>
<?php 
    $country_array = array("INDIA","PAKISTAN","CHINA");
?>
<h1>Ajax Dropdowns Country, State, City</h1>
    <div class="form_container">
        <div class="inner_div">
        <form>
            <div class="input_row">
                <label>Country</label>
                <div class="input_fields">
                    <select class="select_country">
                        <option value="">-- Select Country --</option>
                        <?php foreach ($country_array as $countryname) { ?>
                        <option value="<?php echo $countryname;?>"><?php echo $countryname;?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>
            <div class="input_row">
                <label>State</label>
                <div class="input_fields">
                    <select class="select_state">
                        <option value="">-- Select Country --</option>
                    </select>
                </div>
            </div>
            <div class="input_row">
                <label>City</label>
                <div class="input_fields">
                    <select class="select_city">
                        <option value="">-- Select State --</option>
                    </select>
                </div>
            </div>
        </form>
    </div>
    </div>
</body>
</html>

2. Create second file which is used to process Ajax request. Create a file named "process.php" and copy below code to it.
<?php 
    $state_array = array("INDIA"=>array("Delhi","Gujarat","Rajasthan","Maharastra"),
        "PAKISTAN"=>array("Sindh","Punjab"),
        "CHINA"=>array("China state 1","China state 2"));
    $city_array = array("Delhi"=>array("New Delhi","CP","Chanakyapuri"),
        "Gujarat"=>array("Ahmedabad","Katchch","Vadodara","Rajkot"),
        "Rajasthan"=>array("Jaipur","Pushkar","Udaypur"),
        "Maharastra"=>array("Mumbai","Pune","Nagpur"),
        "Sindh"=>array("Sindh City 1","Sindh city 2"),
        "Punjab"=>array("Punjab city 1","Punjab city 2"),
        "China state 1"=>array("China s1 c1","China s1 c2"),
        "China state 2"=>array("China s2 c1","China s2 c2")
        );
    if(isset($_POST['country'])!=""){
        $country = $_POST["country"]; ?>
        <option value="">-- Select State --</option>
        <?php foreach ($state_array[$country] as $statename) { ?>
        <option value="<?php echo $statename;?>"><?php echo $statename;?></option>
        <?php } ?>
    <?php }

    if(isset($_POST['state'])!=""){
        $state = $_POST["state"]; ?>
        <option value="">-- Select City --</option>
        <?php foreach ($city_array[$state] as $cityname) { ?>
        <option value="<?php echo $cityname;?>"><?php echo $cityname;?></option>
        <?php } ?>
    <?php }
?>
<?php } ?> 

You're done. Enjoy the code. Suggestions are welcomed. Tutorial is very basic, there are not any security rules implemented. The code is just for basic understanding of Dropdown manipulation. Please fill free to ask question in the comment box below. Enjoy...!