Показать все значения, возвращенные из запроса AJAX - PullRequest
0 голосов
/ 04 февраля 2020

У меня есть запрос для выбора данных из моей базы данных:

function check_po_kode() 
{
  $key = $this->input->post('key');
  $this->db->select('a.NO, b.quantity, b.satuan, b.harga, b.discount, b.sparepart_kode, b.sparepart_name, c.id as id_sparepart');
  $this->db->from('purchase_order a');
  $this->db->join('purchase_order_item b', 'a.id = b.purchase_order_id');
  $this->db->join('sparepart c', 'c.kode = b.sparepart_kode');
  $this->db->where(array('a.NO'=>$key));
  $result = $this->db->get()->row_array();

  if (count($result) > 0)
  {
    echo json_encode(array('status'=> 1, 'qty_po'=> $result['quantity'], 'satuan'=> $result['satuan'], 'harga'=> $result['harga'], 'discount'=> $result['discount'], 'sparepart_name'=> $result['sparepart_name'], 'sparepart_kode'=> $result['sparepart_kode'], 'id_sparepart'=> $result['id_sparepart'], 'jmlhSparepart'=> $result['jmlhSparepart']));
  }
  else
  {
    echo json_encode(array('status'=> 0));
  }
}

У меня уже есть результат. Затем я хочу показать данные на странице с этим AJAX кодом:

//check purchase order kode
$("#purchase-order-kode").blur(function() {
  var key = $(this).val();
  $.ajax({
    url: '<?php echo   base_url('
    purchase_order / check_po_kode '); ?>',
    type: 'post',
    dataType: 'json',
    data: {
      key: key
    },
    error: function() { },
    success: function(res) {
      console.log(res);
      if (res.status == 1) {
        $("#purchase-order-kode-notif").html("Valid");
        $('#form').find('#sparepart_id').val(res.id_sparepart);
        $('#form').find('#sparepart_kode').val(res.sparepart_kode);
        $('#form').find('#sparepart_name').val(res.sparepart_name);
        $('#form').find('#quantity').val(res.qty_po);
        $('#form').find('#unit').val(res.satuan);
        $('#form').find('#price').val(res.harga);
        $('#form').find('#discount').val(res.discount);
        $('#button_post').prop('disabled', false);
      } else {
        $("#purchase-order-kode-notif").html("Invalid Kode!");
        $('#button_post').prop('disabled', true);
      }
    }
  });
});
<div class="transport-row form-box" style="display: inline-block; width: 1250px">
  <h4>Input Item</h4>
  <div style="margin-bottom: 20px"></div>
  <div class="row-fluid sparepart-row">
    <div class="control-group">
      <div class="span4">
        <fieldset>
          <label>Nama Barang</label>
          <input type="hidden" name="sparepart_id[]" id="sparepart_id">
          <input type="text" name="sparepart_kode[]" class="stok_barang_id" id="sparepart_kode" placeholder=" Kode" readonly style="width: 100px; padding-bottom:4px;">
          <div class="input-append">
            <input type="text" name="sparepart_name[]" class="stok_barang_name" id="sparepart_name" readonly placeholder="Sparepart name" title="" style="padding-bottom:4px;">
            <span class="add-on">
                                    <a href="#" class="searchBarang" id="0" count="0"><i data-title=""  ime-icon="icon-time" data-date-icon="icon-search" class="icon-search"></i></a>
                                </span>
          </div>
        </fieldset>
      </div>
      <div class="span1 span-qty">
        <fieldset>
          <label>Quantity</label>
          <input type="text" name="quantity[]" id="quantity" class="quantity" placeholder="99" style="width:65px;" />
        </fieldset>
      </div>
      <div class="span1 span-qty">
        <fieldset>
          <label>Unit</label>
          <input type="text" id="unit" class="unit" placeholder="Unit" style="width: 65px;" readonly/>
        </fieldset>
      </div>
      <div class="span2 span-harga">
        <fieldset>
          <label>Price</label>
          <input type="text" name="price[]" id="price" class="price" value="" placeholder="999" style="width:160px;" readonly/>
        </fieldset>
      </div>
      <div class="span3 span-harga">
        <fieldset>
          <label>Discount</label>
          <input type="text" name="discount[]" id="discount" class="discount" value="" placeholder="10%" style="width:160px;">
          <button class="btn btn-primary" id="add_row">+</button>
        </fieldset>
      </div>
    </div>
  </div>
</div>

С помощью приведенного выше кода мне удается показать только 1 элемент данных. Если я выполню этот запрос с номером PO, будет возвращено 2 или 3 элемента. Как я могу показать все данные из запроса AJAX выше?

РЕДАКТИРОВАТЬ: Я уже пытался с:

//check purchase order kode
$("#purchase-order-kode").blur(function(){
var key     = $(this).val();
$.ajax({
url         : '<?php echo base_url('purchase_order/check_po_kode'); ?>',
type        : 'post',
dataType    : 'json',
data        : {key:key},
error       : function(){
},
success     : function(res){
console.log(res);
if(res.status == 1){
$("#purchase-order-kode-notif").html("Valid");                             $.each(res,function(index,item){                                  $('#form').find('#sparepart_id').text(item.id_sparepart),                                   $('#form').find('#sparepart_kode').text(item.sparepart_kode),                                    $('#form').find('#sparepart_name').text(item.sparepart_name),                                   $('#form').find('#quantity').text(item.qty_po),                                   $('#form').find('#unit').text(item.satuan),                                   $('#form').find('#price').text(item.harga),                                    $('#form').find('#discount').text(item.discount);                                 
});
$('#button_post').prop('disabled', false);
}else{
$("#purchase-order-kode-notif").html("Invalid Kode!");
$('#button_post').prop('disabled', true);
}
}
});
});

с кодом выше, я не могу показать какие-либо данные.

1 Ответ

2 голосов
/ 04 февраля 2020

Я думаю, что-то вроде этого может помочь:

Object.keys(res).forEach(function(item) {
    let field = $('#form').find('#' + item);
    if (field) field .val(res[item])
})

, если ваш 'res' - это просто значения полей, то с помощью этого кода вы можете динамически заполнять все поля.

здесь образец фрагмента:

const res = {
  status: 1,
  quantity: "1",
  unit: "pcs",
  price: "59000000",
  discount: "0",
  sparepart_name: "SHOCK",
  sparepart_kode: "MDBUS",
  sparepart_id: "2120"
};
$(function() {
  $(document).ready(function() {
    Object.keys(res).forEach(function(item) {
      let field = $('#' + item);
      if (field) field.val(res[item])
    })
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="transport-row form-box" style="display: inline-block; width: 1250px">
  <h4>Input Item</h4>
  <div style="margin-bottom: 20px"></div>
  <div class="row-fluid sparepart-row">
    <div class="control-group">
      <div class="span4">
        <fieldset>
          <label>Nama Barang</label>
          <input type="hidden" name="sparepart_id[]" id="sparepart_id">
          <input type="text" name="sparepart_kode[]" class="stok_barang_id" id="sparepart_kode" placeholder=" Kode" readonly style="width: 100px; padding-bottom:4px;">
          <div class="input-append">
            <input type="text" name="sparepart_name[]" class="stok_barang_name" id="sparepart_name" readonly placeholder="Sparepart name" title="" style="padding-bottom:4px;">
            <span class="add-on">
                                    <a href="#" class="searchBarang" id="0" count="0"><i data-title=""  ime-icon="icon-time" data-date-icon="icon-search" class="icon-search"></i></a>
                                </span>
          </div>
        </fieldset>
      </div>
      <div class="span1 span-qty">
        <fieldset>
          <label>Quantity</label>
          <input type="text" name="quantity[]" id="quantity" class="quantity" placeholder="99" style="width:65px;" />
        </fieldset>
      </div>
      <div class="span1 span-qty">
        <fieldset>
          <label>Unit</label>
          <input type="text" id="unit" class="unit" placeholder="Unit" style="width: 65px;" readonly/>
        </fieldset>
      </div>
      <div class="span2 span-harga">
        <fieldset>
          <label>Price</label>
          <input type="text" name="price[]" id="price" class="price" value="" placeholder="999" style="width:160px;" readonly/>
        </fieldset>
      </div>
      <div class="span3 span-harga">
        <fieldset>
          <label>Discount</label>
          <input type="text" name="discount[]" id="discount" class="discount" value="" placeholder="10%" style="width:160px;">
          <button class="btn btn-primary" id="add_row">+</button>
        </fieldset>
      </div>
    </div>
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...