Fill Input Field with Dropdown Selection (PHP - AJAX)

时间:2017-04-08 22:37:51

标签: javascript php html ajax

i'm trying to fill some fields from database using a selected dropdown. I did it with ajax but aparently my code doesn't work because the fields keep empty. Can you help me out please?

HTML

<form class="form-horizontal" method="post" action="">
     <div class="form-group">
      <label class="control-label col-sm-offset-2 col-sm-2" for="boxListaRetiro">Retiro:</label>
      <div class="col-sm-5">
            <select class="form-control" id="boxListaRetiro" name="boxListaRetiro">
                <option>Selecciona Retiro</option>
                <!-- This is filled with a function in javascript and its working just fine -->
                <!-- EXAMPLE ROW <option value="1"> $500 | 2017-04-08</option>-->
            </select>
        </div>
      </div>
      class="form-group">
        <label class="control-label col-sm-offset-2 col-sm-2" for="motivo">Motivo:</label>
        <div class="col-sm-5">
          <textarea class="form-control" id="motivo" name="motivo" placeholder="Motivo del retiro" value="" disabled></textarea>
        </div>
      </div>
      <div class="form-group"> 
        <div class="col-sm-offset-4 col-sm-1">
          <button type="submit" class="btn btn-danger">Anular</button>
        </div>
      </div>
</form>

AJAX

//Ajax when second box change
$('#boxListaRetiro').on('change',function(){
    var idRetiro = $(this).val();
    if(idRetiro){
        $.ajax({
            type:'POST',
            url:'PostData.php',
            data:'idRetiro='+idRetiro,
            success:function(html){
                var valores = JSON.parse(html);
                $('#motivo').html(valores[0].motivo);
            }
        }); 
});

PostData.php

if(isset($_POST["idRetiro"]) && !empty($_POST["idRetiro"])){
   //Get the Data
   $sql = "SELECT monto, motivo FROM retiro WHERE idRetiro = " . 
   $_POST['idRetiro'];
   $result = $mysqli->query($sql);
   $rowCount = $result->num_rows;
   $array = array();

   //Muestro el valor del monto
   if($rowCount > 0){
       while($row = $result->fetch_assoc()){
           $array[] = $row;
       }
       echo json_encode($array);
   }

1 个答案:

答案 0 :(得分:0)

试试这个

$('#monto').parent().html(html);
相关问题