Auto load options when PHP / MySQL option is selected

I have a problem with the code I am working on. I am obviously new to php and mySQL. I want to load a parameter field from mysql database when another option is selected. That is: I have options

<select name=state>
   <option value=Lagos>Lagos</option>
   <option value=Abuja>Abuja</option>
   <option value=Rivers>Rivers</option>


and another set of parameters:

   <select name=City>
   <option value=Lekii>Lekki</option>
   <option value=VI>VI</option>
   <option value=Ikoyi>Ikoyi</option>


I have a database called LOCATION , and tables for state and city I want to load the corresponding list of cities when the state is selected. That is, when I select Lagos, all Lagos cities will be populated in another dropdown menu.

Please note that there are 2 Select fields.

Please help me guys.


source to share

2 answers

Based on application architecture and preferences:

You can make an ajax call to the server every time to get the corresponding cities based on the selected state. Follow the post Autocomplete select box with jQuery and AJAX .


you can preload all state based cities in JSON format and show the corresponding city based on the selected state. See my working example here on the Jsfiddle.

    <script src=""></script>
    <script type="text/javascript">
     // you need to fill this cities value getting data from city table of your DB
cities = {
    "Lagos": ["LagosCity1", "LagosCity2"],
    "Abuja": ["AbujaCity1", "AbujaCity2", "AbujaCity3"],
    "Rivers": ["RiversCity1", "RiversCity2", "RiversCity3"]
$(document).ready(function() {
  $('#state').change(function() {
       var state = $(this).val();
    if(cities[state] && cities[state].length > 0)
     $.each(cities[state], function(i, city) {
            $("<option>").attr("value", city).text(city).appendTo("#Scity");
State: <select id='state' name='state'>
   <option value=0>Select</option>
   <option value='Lagos'>Lagos</option>
   <option value='Abuja'>Abuja</option>
   <option value='Rivers'>Rivers</option>
City: <select id="Scity" name='city'></select>



You can by default display all your cities in the city selection box and filter cities while a state is selected and only show cities belonging to that state, see an example here .



You need to use an Ajax call to get data based on the selected state.



All Articles