使用数据库结果数组codeigniter填充html表单

时间:2017-04-26 11:25:58

标签: javascript php jquery html codeigniter

我有这样的表格:

<form method = "POST" action = "<?php echo base_url('Usercontroller/insert') ?>">
  <div class="form-group">
    <label for="exampleInputEmail1">Apartament</label>
    <select name ="txtApartament1" class="form-control">
        <?php foreach($getEntry as $value) { ?>
        <option><?php echo $value->apartament ?></option>
        <?php }?>
    </select>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Nume</label>
    <input type="text" name ="txtNume" class="form-control" id="exampleInputPassword1" placeholder="Nume">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Persoane</label>
    <input type="text" name ="txtPersoane" class="form-control" id="exampleInputPassword1" placeholder="Personae">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Mp</label>
    <input type="text" name ="txtMp" class="form-control" id="exampleInputPassword1" placeholder="Mp">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Comentariu</label>
    <input type="text" name ="txtComentariu" class="form-control" id="exampleInputPassword1" placeholder="Comentariu">
  </div>
  <button type="submit" class="btn btn-default">Salveaza</button>
</form>  

根据从Apartament字段下拉列表中选择的选项,我想用我从数据库中提取的值填充其他字段,为了获得这个,我做了一个ajax,它将发送选择的选项,就像这样:

$(document).ready(function(){
$( ".form-control" ).change(function() {
    var apartament = $(this).val();
    console.log(apartament);
    $.ajax({ 
        url: 'Usercontroller/apartamentSelection',
        data: apartament,
        type: 'post'
    }).done(function(responseData) {
        console.log('Done: ', responseData);
    }).fail(function() {
        console.log('Failed');
    });
 });
});

在我的控制器中,我使用如下数据返回数组:

public function apartamentSelection() {
    $data= $this->input->post(null, true);
    $apartamentulAles=(array_keys($data)[0]);
    $query = $this->db->query("SELECT * FROM membri WHERE apartament = '".$apartamentulAles."' ");
    $result = $query->result_array();
    print_r($result);
}

我对所选选项的回答在完成函数中看起来像这样:

Done:  Array
(
[0] => Array
    (
        [id] => 5
        [apartament] => 5
        [per_id] => 1
        [nume] => Ion
        [persoane] => 4
        [mp] => 32
        [comentariu] => ddddd
    )

)

如何从我的响应数组中获取值并填充上面的表单,在Nume字段中我应该得到Ion,在Persoane 4中等等?

1 个答案:

答案 0 :(得分:2)

您应该将json响应发送回ajax调用。

echo json_encode($result[0]);

dataType='JSON'电话中使用$.ajax({})属性 然后在你的ajax done方法中获取php在responseData变量

中发送的响应
.done(function(responseData) {
 $('#numeId').val(responseData.nume);
})