jquery – PHP AJAX display a value when certain value is selected in drop down list-ThrowExceptions

Exception or error:

im making a subjects schedule what it does is the user select his/her desired course and the subjects that is offered in the selected course are displayed in the drop down list that part is working fine, the problem is when I select a certain subject I need to show in text field the units of that selected subject the code im about to show here is working but it show as drop down list but I want to make as text field i dont know to make it as a text field.

here is my code

select subject

<select name="subject" id="subject1" class="form-control m-1">
             <option value="">Select Subject</option>
</select>

part where I want to show subject unit

<input name="unit" id="unit1" class="form-control m-1">


AJAX for subject

 $(document).ready(function(){
    $('#subject1').change(function(){
      var subject=$(this).val();
      $.ajax({
        url:"fetch_unit.php",
        method:"post",
        data:{Units:subject},
        dataType:"text",
        success:function(data)
        {
          $('#unit1').val(data);
        }
      });

    });
  });

fetch_unit.php

<?php
include 'admin/includes/server.php';

$output='';
$sql="SELECT * FROM tbl_subject";
$result=mysqli_query($conn,$sql);

 $row=mysqli_fetch_array($result);

    echo $output=$row["units"];



?>
How to solve:
 $(document).ready(function(){
   $('#subject1').change(function(){
      var subject=$(this).val();
      $.ajax({
       url:"fetch_unit.php",
       method:"post",
       data:{Units:subject},
       dataType:"text",
      success:function(data){
        $('#unit1').append(data);
      }
    });
 });
});

Answer´╝Ü

You need to modify AJAX success() function:

success:function(data)
{ 
    $('#unit1').text(data);   // fill #unit1 with PHP response data
}

And in PHP use implode() for creating a string:

$row = [];
while ($row=mysqli_fetch_array($result)) {
     $row[] = $row['units'];
}
echo isset($_POST['units']) && $_POST['units'] ? rtrim(implode(', ',$row),', ') : '';  
$(()=>{

    $('#subject1').change(function(){

        var subject=$(this).val();

        $.ajax({
          url:"fetch_unit.php",
          method:"post",
          data:{units:subject}, 
          success:function(data)
          {
              $('#unit1').html('');
              $('#unit1').text(data);
          }
        });

    });
});
<select name="subject" id="subject1" class="form-control m-1">
             <option value="">Select Subject</option>
             <option value="Subject">Subject</option>
</select>

<div id='unit1' class="form-control m-1"></div> 

In PHP you can use $_POST['units'] variable, which contains #subject1 value

Leave a Reply

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