how to append option element and value inside PHP and call inside ajax to html

Viewed 62

I have two <select>, What I want to achieve is that when I select a data, it calls the ajax that I did then append it's value from another <select element and then it has <option>.I tried to alert and the success alerts the <option>, however when I tried to append it to HTML, it says [object Object], I hope someone can help, and explain to me so that in the future whenever I will encounter problems like this I have a backtrack. Thank you so much.

PHP code is here:

echo '<option value="'.$row['name'].'">'. $row['name'] .'</option>';

HTML and JQuery

function setDept(element) {
  let dept = $(element).val();
  if (dept) {

    $.ajax({
      type: "post",
      url: "myform.php",
      data: {
        "department": dept
      },
      success: function(response) {
        // alert(response);
        $('#sel_requested_dept').append(response);
      }
    });

  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="form-group">
  <label> Teacher: </label>
   <select class="form-control selectpicker" name="teacher"
    data-live-search="true" onchange="setDept(this)" required>
    <option value="" selected disabled> Select Teacher </option>
     <?php
       $query = "SELECT * FROM teachers";
       $con->next_result();
       $result=mysqli_query($con,$query);
       if(mysqli_num_rows($result)>0)
       {
          while($row=mysqli_fetch_assoc($result))
          {
                echo '<option value="'.$row['teacher_name'].'">'. $row['section'] ." - ".  
                $row['teacher_name'] .'</option>';
          }
       }                                               
      ?>
     </select>
   </div>    

<div class="form-group">
  <label> Department </label>
  <select name="request_dept" id="sel_requested_dept" class="form-control selectpicker" data-live-search="true" required>
    <option value="" selected disabled> Select Department </option>

  </select>
</div>

0 Answers
Related