简体   繁体   中英

Help using JS dropdown for country/state with PHP

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.

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.

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.

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

Here is the JS (some code trimmed for brevity):

// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
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 < 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 < 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 < 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 && 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 && 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();
}

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

<?php
include 'dbc.php';
page_protect();

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

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

    foreach ($_POST as $key => $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]'");
?>

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

        <table>
            <tr>
                <th>Country:</th>

                <td><select id='countrySelect' name='country' onchange='populateState()'>
                    </select></td>
            </tr>

            <tr>
                <th>State:</th>

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

One of the issues i often run into with Javascript is the load order.

You appear to be running and calling populateCountry and populateState at the same time, thereby not having much opportunity for the State list to be populated once the country list has been determined.

Consider moving "populateState()" to the last line of "populateCountry()" so it calls it at the end of the function processing.

There are multiple ways to do this, but this is the simplest to illustrate the point.

Change the top lines

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

to

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

Does that not work?

PHP Short tags, ie " <?= " are not enabled by default anymore i believe in some of the newer php versions. I've stopped using it, i know it looks pretty but it can be a pain if you migrate to a server that doesn't support them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM