By Mitchell Harper
Most eCommerce shops on the Internet require you to choose your country and state when checking out to provide you with shipping costs. Instead of reloading the page to get a list of states after you choose your country, we can use AJAX to do the same thing -- minus the page refresh.
Create a new page called country.php and copy and paste the code below:
<?php
$states = array();
$states["Australia"] = array("New South Wales", "Queensland", "Victoria", "South Australia", "Tasmania", "Western Australia", "Northern Territory");
$states["USA"] = array("California", "New York", "Ohio", "Colorado", "Florida", "Texas", "Arizona", "Washington");
if(isset($_POST["country"]) && isset($states[$_POST["country"]]))
{
foreach($states[$_POST["country"]] as $state)
{
printf("%s,", $state);
}
}
?>
The PHP above creates an array of states: One for Australia and one for USA. When a country is passed to the script (from our AJAX function using JavaScript), the appropriate states are returned in a comma-separated value string, such as: State1,State2,State3.
Our HTML file will be called country.html. It looks like this:
<html>
<head>
<script>
var url = "country.php";
var what = "SetStates(req.responseText)";
function GetStates(Country)
{
DoCallback("country="+Country);
}
function SetStates(States)
{
var stateBox = document.getElementById("state");
stateBox.options.length = 0;
if(States != "")
{
var arrStates = States.split(",");
for(i = 0; i < arrStates.length; i++)
{
if(arrStates[i] != "")
{
stateBox.options[stateBox.options.length] = new Option(arrStates[i], arrStates[i]);
}
}
}
}
</script>
<script src="ajax.js" type="text/javascript"></script>
</head>
<body>
<pre>Country: <select onChange="GetStates(this.options[this.selectedIndex].text)" id="country"><option value=""></option><option>Australia</option><option>USA</option></select><br>State: <select id="state"></select>
</pre>
</body>
</html>
When you choose a country, the AJAX function will retrieve a list of states for that country from the country.php file using AJAX. It will then pass the list of states back to our SetStates function:
var url = "country.php";
var what = "SetStates(req.responseText)";