Dynamic Dependent Dropdown with Vue.js and PHP

Auto-populating records based on the selection make easier to control the flow of inputs and the user is restricted on the selection.

Data is updated on dependent dropdown according to parent dropdown selection.

To send AJAX request in Vue.js I am using Axios package.

In this tutorial, I create 3 dependent dropdowns for the country, state, city and send AJAX request to load records whenever dropdown value changes with Vue.js and PHP.

Dynamic dependent dropdown with Vue.js and PHP


Contents

  1. Table structure
  2. Configuration
  3. Download & Include
  4. HTML
  5. PHP
  6. Script
  7. Demo
  8. Conclusion

1. Table structure

I am using 3 tables in the example –

countries table (Store counties records) –

CREATE TABLE `countries` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

states table (Store states of the countries) –

CREATE TABLE `states` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  `country` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

cities table (Store cities of the states) –

CREATE TABLE `cities` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  `state` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Configuration

Create a new config.php to define database connection.

Completed Code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. Download & Include

  • Download Axios package from GitHub. or you can also use CDN (https://unpkg.com/axios/dist/axios.min.js).
  • Now, include axios.min.js with vue.js in the <head> section.
<script src="vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

4. HTML

Create 3 <select > elements –

  • The first <select>  element use to display countries. Add v-model='country' and @change event to get the states when an option selected. Use v-for='data in countries' to add <option >.
  • The second <select > element used to display states of a selected country. Add v-model='state' and @chage event to get the cities when an option selected. Use v-for='data in states' to add <option >.
  • The third <select > element used to display cities of a selected state. Use v-for='data in cities' to add <option >.

Completed Code

<div id='myapp'>

  <table>
    <tr>
      <td>Country</td>
      <td>
        <select v-model='country' @change='getCountryStates()'>
          <option value='0' >Select Country</option>
          <option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
        </select>
      </td>
    </tr>

    <tr>
      <td>State</td>
      <td>
        <select v-model='state' @change='getStateCities()'>
          <option value='0' >Select State</option>
          <option v-for='data in states' :value='data.id'>{{ data.name }}</option>
        </select>
      </td>
    </tr>

    <tr>
      <td>City</td>
      <td>
        <select v-model='city' >
          <option value='0' >Select City</option>
          <option v-for='data in cities' :value='data.id'>{{ data.name }}</option>
        </select>
      </td>
    </tr>
  </table>

</div>

5. PHP

Create a new ajaxfile.php file.

Fetch records according to $request –

  • If $request == 1 – Fetch all records from countries table and initialize $response Array. Return $response in JSON format.
  • If $response == 2 – Fetch all records from states table according to $country value and initialize $response Array.
  • If $response == 3 – Fetch all records from cities table according to $state value and initialize $response Array.

Completed Code

<?php
include "config.php";

$request = $_GET['request'];

// Fetch Countries
if($request == 1){

  $result = mysqli_query($con,"SELECT * FROM countries");

  $response = array();
  while($row = mysqli_fetch_assoc($result)){
    $id = $row['id'];
    $name = $row['name'];

    $response[] = array("id"=>$id,"name"=>$name);
  }

  echo json_encode($response);
  exit;
}

// Fetch States of a Country
if($request == 2){
  $country = $_GET['country'];
  $result = mysqli_query($con,"SELECT * FROM states WHERE country=".$country);

  $response = array();
  while($row = mysqli_fetch_assoc($result)){
    $id = $row['id'];
    $name = $row['name'];

    $response[] = array("id"=>$id,"name"=>$name);
  }

  echo json_encode($response);
  exit;
}

// Fetch Cities of a State
if($request == 3){
  $state = $_GET['state'];
  $result = mysqli_query($con,"SELECT * FROM cities WHERE state=".$state);

  $response = array();
  while($row = mysqli_fetch_assoc($result)){
    $id = $row['id'];
    $name = $row['name'];

    $response[] = array("id"=>$id,"name"=>$name);
  }

  echo json_encode($response);
  exit;
}

6. Script

Define 6 data variables – country, countries, state, states, city, and cities.

Define 3 methods –

  • getCountry – Use this method to get all countries for this send axios.get request where pass request: 1. On successful callback assign response.data in app.countries.
  • getCountryStates – Use this method to get all states of the selected country. Send axios.get request where pass request: 2, country: this.country. On successful callback assign response.data in app.states.
  • getStateCities – Use this method to get all cities of the selected state. Send axios.get request where pass request: 3, state: this.state. On successful callback assign response.data in app.cities.

With created option call this.getCountry to load country dropdown after the instance is been created.

Completed Code

var app = new Vue({
  el: '#myapp',
  data: {
    country: 0,
    countries: '',
    state: 0,
    states: '',
    city: 0,
    cities: ''
  },
  methods: {
    getCountry: function(){

      axios.get('ajaxfile.php', {
        params: {
          request: 1
        }
      })
      .then(function (response) {
         app.countries = response.data;

         // Empty state and city
         app.states = '';
         app.cities = '';
         app.state = 0;
         app.city = 0;
      });

    },
    getCountryStates: function(){

      axios.get('ajaxfile.php', {
         params: {
           request: 2,
           country: this.country
         }
      })
      .then(function (response) {
         app.states = response.data;
         app.state = 0;

         // Empty city
         app.cities = '';
         app.city = 0;
      }); 
    }, 
    getStateCities: function(){

      axios.get('ajaxfile.php', { 
        params: {
          request: 3,
          state: this.state
        }
      }) 
      .then(function (response) {
        app.cities = response.data;
        app.city = 0;
      }); 
    }
  },
  created: function(){
    this.getCountry();
  }
})

7. Demo

Select a country from the first drop-down then select the state from the second drop-down.


8. Conclusion

In the example, I used change event to auto-populate data on <select > element similarily you can dynamically load data on any other elements like textbox, textarea using any other event – keyup, keydown, click.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 2
  •  
  •  
  •  
  •  
  •  

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *