Jump to content

Recommended Posts

I have a pair of ajax country / state select boxes that I want to autopopulate from the users profile. The country is selected from a db query, but I can't figure out how to have it select the state too. On page load the countries are listed and the users country selected, but the state select doesn't recognize that it's already populated.

 

Here's my code...any help would be appreciated:

 

ajax

<script type="text/javascript">
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
try { return new XMLHttpRequest(); } catch(e) {}
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText;
}
}
};
req.open("GET", "country.php?data="+src+"&val="+val);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1");
req.send(null);
}
window.onload=dochange('country', -1);
	 </script>

 

fields:

<tr>
<td><strong>Country</strong></td>
<td><span id="country"></span></td>
</tr>
<tr>
<td><strong>State</strong></td>
<td><span id="state"><input name="state" type="text" value="" /></span></td>
</tr>

 

country.php

<?php
include ('includes/functions.php');
$data = $_GET['data'];
$val = $_GET['val'];
if ($data == 'country') {
echo "<select name='country' onchange=\"dochange('state', this.value)\">\n";
echo "<option value='0'>===Choose a country===</option>\n";
$query = "SELECT `id`, `iso`, `country` FROM regions ORDER BY `country`";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
if ($result->num_rows > 0) {
 while ($row = $result->fetch_assoc()) {
	 echo "<option value='" . $row['id'] . "' " . ($customer['country'] == $row['iso'] ? 'selected=\"selected\"' : '') . " >" . $row['country'] . "</option> \n";
 }
}
} else if ($data == 'state') {
$query = "SELECT id,region_id,name FROM subregions WHERE region_id = '$val'";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
if ($result->num_rows > 0) {
 echo "<select name='state' >\n";
 echo "<option value='0'>====Choose State ====</option>\n";
 while ($row = $result->fetch_assoc()) {
	 echo "<option value='" . $row['name'] . "' >" . $row['name'] . "</option> \n";
 }
} else {
 echo "<input name=\"state\" type=\"text\" name=\"other\" value='Other' \">";
}
}
echo "</select>\n";
?>

Edited by quasiman

Alright, no response....still working on this. I've switched to jquery, but same results - I can't see how to autoselect the state when a country is preselected. See my new code below:

 

jquery

<script src="<? echo _TEMPLATE;?>/js/jquery-1.7.2.min.js" type="text/javascript"></script>
		    <script type="text/javascript">
			    $(document).ready(function()
			    {
				    $(".country").change(function()
				    {
					    var dataString = 'id='+ $(this).val();
					    $.ajax
					    ({
						    type: "POST",
						    url: "state.php",
						    data: dataString,
						    cache: false,
						    success: function(html)
						    {
							    $(".state").html(html);
						    }
					    });
				    });
			    });
		    </script>

 

fields:

<tr>
   <td><strong>Country</strong></td>
   <td><select name="country" class="country">
   <option selected="selected">--Select Country--</option>
   <?php
       $query = "SELECT `id`, `iso`, `country` FROM regions ORDER BY `country`";
       $result = $mysqli->query($query) or die($mysqli->error . __LINE__);
       if ($result->num_rows > 0) {
           while ($row = $result->fetch_assoc()) {
               echo "<option value='" . $row['id'] . "' " . ($customer['country'] == $row['iso'] ? 'selected=\"selected\"' : '') . " >" . $row['country'] . "</option> \n";
           }
       }
   ?>
   </select></td>
</tr>

 

state.php

<?php
include ('includes/functions.php');
if($_POST['id'])
{
$id=$_POST['id'];
   $query = "SELECT id,region_id,name FROM subregions WHERE region_id = '$id'";
   $result = $mysqli->query($query) or die($mysqli->error . __LINE__);
   if ($result->num_rows > 0) {
    echo "<select name='state' >\n";
    echo "<option value='0'>====Choose State ====</option>\n";
    while ($row = $result->fetch_assoc()) {
	    echo "<option value='" . $row['name'] . "' >" . $row['name'] . "</option> \n";
    }
   } else {
    echo "<input name=\"state\" type=\"text\" name=\"other\" />";
   }
}
?>

Nevermind, I got it...

 

$(document).ready(function()
{
   $(".country").change(function()
   {
       var dataString = 'id='+ $(this).val();						   
       $.ajax
       ({
           type: "POST",
           url: "state.php",
           data: dataString,
           cache: false,
           success: function(html)
           {
               $(".state").html(html);
           }
       });
   });
   $(".country").change(function() {  // bind a change event:
       $(this).val();
   }).change(); // and trigger a "change" event immediately
});

Edited by quasiman
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.