Help using JS dropdown for country/state with PHP
<p>Here's the issue: I have a JS dropdown for country and state that runs in a PHP form for users to update their profiles.</p>

<p>The user selects country for ex 'USA', then state 'Colorado', and submits. What happens is that these values are saved OK on my database, but when the page refreshes, only the country dropdown remains selected with the user's choice. The state shows as 'Select State', although the value 'Colorado' is in the DB.</p>

<p>I just can't manage to have PHP and JS talk to each other so that if the user chose Colorado, it should be pulled from the DB and shown as selected whenever they refresh or come back to the page.</p>

<p>Any ideas how to do this? I tried the suggestion at the top of the JS code but was unsuccessful.</p>

<p>Here is the JS (some code trimmed for brevity):</p>

<pre><code>// If you have PHP you can set the post values like this
//var postState = '&lt;?= $_POST["state"] ?&gt;';
//var postCountry = '&lt;?= $_POST["country"] ?&gt;';
var postState = '';
var postCountry = '';

// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:Alaska:Alaska|\
US:Alabama:Alabama|\
';

var country = '\
US:United States|\
CA:Canada|\
';

function TrimString(sInString) {
  if ( sInString ) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
  }
}

// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry) {
  if ( postCountry != '' ) {
    defaultCountry = postCountry;
  }
  var countryLineArray = country.split('|');  // Split into lines
  var selObj = document.getElementById('countrySelect');
  selObj.options[0] = new Option('Select Country','');
  selObj.selectedIndex = 0;
  for (var loop = 0; loop &lt; countryLineArray.length; loop++) {
    lineArray = countryLineArray[loop].split(':');
    countryCode  = TrimString(lineArray[0]);
    countryName  = TrimString(lineArray[1]);
    if ( countryCode != '' ) {
      selObj.options[loop + 1] = new Option(countryName, countryCode);
    }
    if ( defaultCountry == countryCode ) {
      selObj.selectedIndex = loop + 1;
    }
  }
}

function populateState() {

  var selObj = document.getElementById('stateSelect');
  var foundState = false;
  // Empty options just in case new drop down is shorter
  if ( selObj.type == 'select-one' ) {
    for (var i = 0; i &lt; selObj.options.length; i++) {
      selObj.options[i] = null;
    }
    selObj.options.length=null;
    selObj.options[0] = new Option('Select State','');
    selObj.selectedIndex = 0;
  }
  // Populate the drop down with states from the selected country
  var stateLineArray = state.split("|");  // Split into lines
  var optionCntr = 1;
  for (var loop = 0; loop &lt; stateLineArray.length; loop++) {
    lineArray = stateLineArray[loop].split(":");
    countryCode  = TrimString(lineArray[0]);
    stateCode    = TrimString(lineArray[1]);
    stateName    = TrimString(lineArray[2]);
  if (document.getElementById('countrySelect').value == countryCode &amp;&amp; countryCode != '' ) {
    // If it's a input element, change it to a select
      if ( selObj.type == 'text' ) {
        parentObj = document.getElementById('stateSelect').parentNode;
        parentObj.removeChild(selObj);
        var inputSel = document.createElement("SELECT");
        inputSel.setAttribute("name","state");
        inputSel.setAttribute("id","stateSelect");
        parentObj.appendChild(inputSel) ;
        selObj = document.getElementById('stateSelect');
        selObj.options[0] = new Option('Select State','');
        selObj.selectedIndex = 0;
      }
      if ( stateCode != '' ) {
        selObj.options[optionCntr] = new Option(stateName, stateCode);
      }
      // See if it's selected from a previous post
      if ( stateCode == postState &amp;&amp; countryCode == postCountry ) {
        selObj.selectedIndex = optionCntr;
      }
      foundState = true;
      optionCntr++
    }
  }
  // If the country has no states, change the select to a text box
  if ( ! foundState ) {
    parentObj = document.getElementById('stateSelect').parentNode;
    parentObj.removeChild(selObj);
  // Create the Input Field
    var inputEl = document.createElement("INPUT");
    inputEl.setAttribute("id", "stateSelect");
    inputEl.setAttribute("type", "text");
    inputEl.setAttribute("name", "state");
    inputEl.setAttribute("size", 30);
    inputEl.setAttribute("value", postState);
    parentObj.appendChild(inputEl) ;
  }
}

function initCountry(country) {
  populateCountry(country);
  populateState();
}
</code></pre>

<p>and here is the PHP/HTML (trimmed a bit):</p>

<pre><code>&lt;?php
include 'dbc.php';
page_protect();

$err = array();
$msg = array();

if ($_POST['doUpdate'] == 'Update') {

    foreach ($_POST as $key =&gt; $value) {
        $data[$key] = filter($value);
    }

    $country =          $data['country'];
    $state =            $data['state'];

    mysql_query("UPDATE users SET
    `country` =         '$data[country]',
    `state` =           '$data[state]'

     WHERE id='$_SESSION[user_id]'
    ") or die(mysql_error());

    $msg[] = "Your Profile has been updated";
    //header("Location: mysettings.php?msg=Your new password is updated");

}

$rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'");
?&gt;

&lt;html&gt;
&lt;body&gt;
    &lt;form name="profile_form" id="profile_form" method="post" action=""&gt;
        &lt;?php while ($row_settings = mysql_fetch_array($rs_settings)) {?&gt;
        &lt;input name="doUpdate" type="submit" id="doUpdate" value="Update"&gt;

        &lt;table&gt;
            &lt;tr&gt;
                &lt;th&gt;Country:&lt;/th&gt;

                &lt;td&gt;&lt;select id='countrySelect' name='country' onchange='populateState()'&gt;
                    &lt;/select&gt;&lt;/td&gt;
            &lt;/tr&gt;

            &lt;tr&gt;
                &lt;th&gt;State:&lt;/th&gt;

                &lt;td&gt;
                    &lt;select id='stateSelect' name='state'&gt;
                    &lt;/select&gt; 
                        &lt;script type="text/javascript"&gt;
                            initCountry('&lt;?php echo $row_settings['country']; ?&gt;'); 
                    &lt;/script&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
        &lt;/table&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
