pjustindaryll
pjustindaryll

Reputation: 377

Populating 3 dropdown using ajax, one after the other

I currently have this code that populates one dropdown using the value from previous dropdown, my problem now is how will I populate the 3rd dropdown using the result from the 2nd dropdown that was provided by the first dropdown?

This the current code.

accounttype will be the first dropdown. accountcode will be the second dropdown based on the result of accounttype. accounttitle should be the third dropdown based on the result of accountcode .

<div class="">
    <label>accounttype :</label>
    <select name="accounttype" id="accounttype">
      <option value=''>------- Select --------</option>
      <?php 
      $sql = "SELECT DISTINCT accounttype from earningsamendmentaccount";

      include 'query/sqlsrv_query-global.php';

      if(sqlsrv_num_rows($query) > 0) {
        while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
          echo "<option value='".$row['accounttype']."'>".$row['accounttype']."</option>";
        }
      }
      ?>
    </select>

<label>accountcode :</label>
<select name="accountcode" id="accountcode"><option>------- Select --------</option></select>

<label>accounttitle :</label>
<select name="accounttitle" id="accounttitle"><option>------- Select --------</option></select>

  </div>

This is currently my ajax. This is within the same pag as my <div>

<script>
  $(document).ready(function() {
  $("#accounttype").change(function() {
    var accounttype = $(this).val();
    if(accounttype != "") {
      $.ajax({
        url:"earnings_amendment-employee_select.php",
        data:{accountcode:accounttype},
        type:'POST',
        success:function(response) {
          var resp = $.trim(response);
          $("#accountcode").html(resp);
        }
      });
    } else {
      $("#accountcode").html("<option value=''>------- Select --------</option>");
    }
  });
});
</script>

This is my earnings_amendment-employee_select.php .

<?php
include 'includes/session.php';
if(isset($_POST['accountcode'])) {
    $accountcode=$_POST['accountcode'];
  $sql = "select accountcode, accounttitle from earningsamendmentaccount where accounttype='$accountcode'";

      $query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));

  if(sqlsrv_num_rows($query) > 0) {
    echo "<option value=''>------- Select --------</option>";
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
          echo "<option value='".$row['accountcode']."'>".$row['accountcode']."</option>";
    }
  }
} else {
  header('location: ./');
}
?>

What would be the best approach to do this to populate my third dropdown column? I tried creating a separate ajax for accounttitle but it didn't work.

Upvotes: 0

Views: 138

Answers (1)

Karma Blackshaw
Karma Blackshaw

Reputation: 942

have you tried

$('#your_second_dropdown').on('change', ()=> {

// your code here...

})

Upvotes: 1

Related Questions