So I’ve got a website with two HTML drop-down lists- one is a list of US states, the other is a list of the cities/towns in the selected state. As of right now, I have a file for each state, and they all have the options listed as such:
<option value="44.729932, -72.381758">Albany</option>
<option value="44.976728, -73.30257">Alburg</option>
The value is the city/town’s coordinates. I can’t have all this data downloaded at once (well I guess I could but it’s 1MB and I’m serving the page on a 130KB/s connection…) so I’d like a way to have each town/city file downloaded once its state name has been selected… I made these files under the assumption I could just do this:
<select name="state" method="get" id="state">
<option value="citiestowns/alabama.html">Alabama</option>
<option value="citiestowns/alaska.html">Alaska</option>
</select>
<select id="cityortown" name="cityortown">
<?php
$state = $_GET['state'];
include("$state");
?>
</select>
But when I do this, I just get the state drop down list and a blank drop down list next to it… heeeeeelp! 🙁
You’ll probably want to use AJAX for this. Thats a technique using PHP and Javascript that allows your page to get new data from the server without a page reload. This will allow your page to initally get only the states from a server and then get the relevant cities and their data from a PHP script.
So you’re going to need
First HTML page. Can be static or PHP generated, but will need some javascript so that once a state is selected from the states drop-down the city drop down will be generated.
a- The original HTML page with state drop down
b- The javascript described above
A PHP script. This page will never be gone to ‘directly’ (you wouldnt type its URL into your browser most likely), but it will be the target of a server request.
Input – Parameter indicating which state
Output – The dropdown with the cities belonging to that state and their values.
You don’t state what form your data is in (im guessinng/hoping a relational DB? Document DB wouldnt be bad, but CSV would be pretty tough) but ill try to paint a rough sketch of the PHP script I describe in step 2.
getcities.php
You can see how this generates the select/option dropdown with only the required elements.
The javascript will be responsibly for calling something like
getcities.php?state='NY'and putting the output into an element of your page (likely a div)Look up Ajax basics for how to do that. Libraries like jQuery can greatly simplify the Ajax.
EDIT – in response to your comments
So on your page you can do something like
Basically, if the format is as you describe, all you need to do is load the contents of a certain HTML file into the
<select>i callcitySelectabove. This can be done entirely by javascript, and with the use of the jQuery library it is pretty much trivial.