Tuesday 25 September 2018

PHP: Populate a dropdown list based on selection of another dropdown list using ajax


This tutorial will you help to populate a dropdown list based on selection of another dropdown option using ajax. What actually we do here, let’s assume we have two dropdown list in a form. The first dropdown list is the list of countries where users can select one country. The second dropdown list will display only the states it belongs to the selected country dynamically through ajax means no page refreshing.


Also, you can enjoy the live demo example on Populate a dropdown list based on selection of another dropdown list using ajax for better understanding. As well as you can get the full source code from the download link.

If you want to generate or populate multiple dropdown lists using Ajax then click on the following article — Populate multiple dropdown lists using Ajax, jQuery, PHP, and MySQL.

Database Tables

  1. CREATE TABLE `countries` (
  2. `id` int(11) NOT NULL,
  3. `country` varchar(255) NOT NULL
  4. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  5. CREATE TABLE `states` (
  6. `id` int(11) NOT NULL,
  7. `country_id` int(11) NOT NULL COMMENT 'id of the countries table',
  8. `state` varchar(255) NOT NULL
  9. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  10. INSERT INTO `countries` (`id`, `country`) VALUES
  11. (1, 'India'),
  12. (2, 'America');
  13. INSERT INTO `states` (`id`, `country_id`, `state`) VALUES
  14. (2, 1, 'West Bengal'),
  15. (3, 1, 'Maharastra'),
  16. (4, 1, 'Goa'),
  17. (5, 1, 'Kerala'),
  18. (6, 2, 'Newyork'),
  19. (7, 2, 'Ohio'),
  20. (8, 2, 'Texas');
For dynamically populate or generate the dropdown list using ajax, you need two tables in the database. The above queries will create two tables and insert some data into these two tables respectively.

Database Connection (db.php)

  1. <?php
  2. define('HOSTNAME','localhost');
  3. define('DB_USERNAME','username');
  4. define('DB_PASSWORD','password');
  5. define('DB_NAME', 'database-name');
  6. //global $con;
  7. $con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
  8. // Check connection
  9. if(mysqli_connect_errno($con)) echo "Failed to connect MySQL: " .mysqli_connect_error();
  10. ?>
Establishing a database connection using PHP is an important part of this example. Replace usernamepassword, and database-name with your credentials.

HTML – Dynamically Populate Dropdown List Using Ajax (index.php)

Let’s follow the below code which lets you help to dynamically generate the dropdown list using ajax.
  1. <script type="text/javascript" src="jquery.min.js"></script>
  2. <script type="text/javascript" src="ajax.js"></script>
  3. <?php include("db.php");?>
  4. <div class="">
  5. <label>Country :</label>
  6. <select name="country" id="country">
  7. <option value=''>------- Select --------</option>
  8. <?php
  9. $sql = "select * from `countries`";
  10. $res = mysqli_query($con, $sql);
  11. if(mysqli_num_rows($res) > 0) {
  12. while($row = mysqli_fetch_object($res)) {
  13. echo "<option value='".$row->id."'>".$row->country."</option>";
  14. }
  15. }
  16. ?>
  17. </select>
  18. <label>State :</label>
  19. <select name="state" id="state"><option>------- Select --------</option></select>
  20. </div>
As you can see above, we created two dropdown list. The first dropdown list is for the country list which is dynamic and it comes from the database during the page load by using a simple PHP code. The second dropdown list will dynamically generate the list of states based on the selection of the country dropdown list using Ajax and PHP.

Ajax Call – Create Dynamic dropdown (ajax.js)

  1. $(document).ready(function() {
  2. $("#country").change(function() {
  3. var country_id = $(this).val();
  4. if(country_id != "") {
  5. $.ajax({
  6. url:"get-states.php",
  7. data:{c_id:country_id},
  8. type:'POST',
  9. success:function(response) {
  10. var resp = $.trim(response);
  11. $("#state").html(resp);
  12. }
  13. });
  14. } else {
  15. $("#state").html("<option value=''>------- Select --------</option>");
  16. }
  17. });
  18. });
When you first select or change any country from the first dropdown list the $(“#country”).change(function() {….}) will come into action. Variable country_id holds the id of the selected country. If it is not null then $.ajax({….}) will send an Ajax post request to the get-states.php page with the country id.

Fetch The List Of The States (get-states.php)

  1. <?php include("db.php"); ?>
  2. <?php
  3. if(isset($_POST['c_id'])) {
  4. $sql = "select * from `states` where `country_id`=".mysqli_real_escape_string($con, $_POST['c_id']);
  5. $res = mysqli_query($con, $sql);
  6. if(mysqli_num_rows($res) > 0) {
  7. echo "<option value=''>------- Select --------</option>";
  8. while($row = mysqli_fetch_object($res)) {
  9. echo "<option value='".$row->id."'>".$row->state."</option>";
  10. }
  11. }
  12. } else {
  13. header('location: ./');
  14. }
  15. ?>
The above code is a simple PHP code which returns the list of states based on the country id from the database. mysqli_real_escape_string() function escapes special characters from a string. It is very useful to prevent SQL injection.

Complete Source Code – Populate a dropdown list based on selection of another dropdown list using ajax

Try the live demo example on Populate a dropdown list based on selection of another dropdown list using ajax. Download the complete source code from the below download link and please like and share the tutorial link with others.

0 comments:

Post a Comment