Wednesday 29 May 2013

How to change states list depending on selected country

This tutorial tell you how to How to change states list depending on selected country.
You should follow these steps:
  1. Create your database connection.e.g.
    <?php
    $con=mysql_connect ("localhost","username","password");
    @mysql_select_db('your_bd') or die(mysql_error());
    // Check connection
    if (!$con)
    {
    echo "Failed to connect to MySQL: ";
    }

    ?>
  2. Create states and country tables.
    CREATE TABLE IF NOT EXISTS `states` ( `stateid` int(11) NOT NULL AUTO_INCREMENT, `state` varchar(32) NOT NULL DEFAULT '', `code` varchar(32) NOT NULL DEFAULT '', `country_code` char(2) NOT NULL DEFAULT '', PRIMARY KEY (`stateid`), UNIQUE KEY `code` (`country_code`,`code`), KEY `state` (`state`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=186 ;

    CREATE TABLE IF NOT EXISTS `country` ( `country_code` char(2) NOT NULL default '', `country_name` varchar(90) NOT NULL default '' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  3. Insert values in tables.
    INSERT INTO `country` (`country_code`, `country_name`) VALUES ('GB', 'United Kingdom (Great Britain)'), ('US', 'United States'), ('PK', 'Pakistan');

    INSERT INTO `states` (`stateid`, `state`, `code`, `country_code`) VALUES (1, 'Aberdeenshire', 'ABd', 'GB'), (2, 'Angus', 'AG', 'GB'), (3, 'Argyll', 'ARg', 'GB'), (4, 'Avon', 'AV', 'GB'), (5, 'Ayrshire', 'AY', 'GB'), (6, 'Alabama', 'AL', 'US'), (7, 'Alaska', 'AK', 'US'), (8, 'Arizona', 'AZ', 'US'), (9, 'Arkansas', 'AR', 'US'), (10, 'California', 'CA', 'US');
  4. Copy code below and create a file named "get_state.php"
    <?php
    // Copy this code and create a file named get_state.php
    include_once('db_connection.php');
    $code = $_GET['code'];
    $result = mysql_query("SELECT * FROM `states` WHERE country_code = '".$code."'");
    if(mysql_num_rows($result) > 0)
    {
    echo '<select name="b_state" id="b_state" style="width:220px;">';
    while($row = mysql_fetch_array($result))
    {
    echo "<option value=".$row['code'].">".$row['state']."</option>";
    }
    echo '</select>';
    }
    else
    {
    echo '<input type="text" size="32" value="" name="b_state" id="b_state">';
    }
    ?>
  5. Copy and past code below and save it as "states.php".
    <?php
    // include your database connection.
    include_once('db_connection.php');
    // // create tables
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <!--don't forget to include jquery-->
    <script src="js/jquery.js"></script>
    <script type="text/javascript">
    function change_state(state)
    {
    // Below is post ajax request which goes to "get_state.php" where state list changes on the base of parameter "code" which is set by user on_change event.
    // then result is passed to '#state_container' id of <td> which is parent of <select> element.
    $.post('get_state.php?code='+state, function(data) {
    $('#state_container').html(data);
    });
    }
    </script>
    </head>
    <body>
    <table width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-bottom:5px;">
    <tbody>
    <tr>
    <td></td>
    <td style="padding-top:15px;">
    <form name="registerform" id="insertform" method="post" action="contact_us.php">
    <table width="100%" cellspacing="0" cellpadding="2">
    <tbody>
    <tr valign="middle">
    <td class="FormButton">County/State</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap" id="state_container">

    <?php
    // Below if else condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_country']))
    $code = $_POST['b_country']; //IF contry selected show states of that country else show states of UK.
    else
    $code = 'GB';
    ////// Query below show the states on the base of country_code.
    $result = mysql_query("SELECT * FROM `states` WHERE country_code = '".$code."'");
    if(mysql_num_rows($result) > 0)
    {
    // IF states exit in database show dropdown else show input text field so that user can enter state manually.
    echo '<select name="b_state" id="b_state" style="width:220px;">';
    while($row = mysql_fetch_array($result))
    {
    // Below if condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_state']))
    echo $selected = ($row['code']==$_POST['b_state']) ? "selected='selected'" : "";
    echo "<option ".$selected." value=".$row['code'].">".$row['state']."</option>";
    }
    echo '</select>';
    }
    else
    {
    // Below if else condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_state']))
    $value = $_POST['b_state'];
    else
    $value = '';
    echo '<input type="text" size="32" value="'.$value.'" name="b_state" id="b_state">';
    }
    ?>

    </td>
    </tr>

    <tr valign="middle">
    <td class="FormButton">Country</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap">
    <!-- Below onchange event calls the change_state() with value of selected Country code-->
    <select onchange="javascript: change_state(this.value);" name="b_country" id="b_country" style="width:220px;">
    <?php
    // Query below showes the list of `countries`.
    $result = mysql_query("SELECT * FROM `country`");
    if(mysql_num_rows($result) > 0)
    {
    while($row = mysql_fetch_array($result))
    {
    // Below if else condition is for the purpose of saving the users selected value if validation error occurs.
    if(isset($b_country))
    $selected = ($row['country_code']==$b_country) ? "selected='selected'" : "";
    else // This is for first time uk will be selected by default.
    $selected = ($row['country_code']=='GB') ? "selected='selected'" : "";

    echo "<option ".$selected." value=".$row['country_code'].">".$row['country_name']."</option>";
    }
    }
    ?>
    </select>
    </td>
    </tr>
    </tbody></table>
    </form>
    </body>
    </html>

1 comments: