Estherons Samuel
Estherons Samuel

Reputation: 61

Auto load options when an option is selected PHP/MySQL

I'm having a problem with a code I'm working on. I'm obviously new to php and mySQL. I want to load an option field from mysql database when another option is selected. That is to say: I have options

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

and another set of options:

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

I have a database called PLACES and tables for state and city I want to Load a corresponding list of cities when I select state. That is, when I select Lagos, all cities in Lagos will be populated in another drop down menu.

Please note that there are 2 Select Fields.

Please help me out, guys.

Upvotes: 3

Views: 3040

Answers (2)

Tapaswi Panda
Tapaswi Panda

Reputation: 1051

Based on your application architecture and preference:

You can do a ajax call to server each time to get corresponding cities based on the state selected. Please follow the post Auto-populating Select Boxes using jQuery & AJAX.

Or

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

<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></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)
    $("#Scity").html('');
     $.each(cities[state], function(i, city) {
            $("<option>").attr("value", city).text(city).appendTo("#Scity");
        });
  });
});
</script>
</head>
<body>
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>
</select>
City: <select id="Scity" name='city'></select>
</body>
</html>

Or

You can by default show all your cities in city select box and filter out cities while a state is selected and only show cities that belongs to that state, please see a kind of example here.

Upvotes: 3

Naincy
Naincy

Reputation: 2943

You need to use Ajax call to get data on the basis of state selected.

Upvotes: 3

Related Questions