Home > Software engineering >  Sending a multidimensional array with ajax
Sending a multidimensional array with ajax

Time:12-27

I have multidimensional array on client side, when I send that array to a PHP server, the array is received as string.

My code like this

 let data_barang = [];
 var nama_barang = $("#nama_barang_add").val();
 var id_barang = $("#nama_barang_add").data("id_barang");
 var perkiraan = $("#nama_barang_add").data("perkiraan");

 var qty = $("#qty_add").val();
 var satuan = $("#satuan_add").val();

 data_barang.push([nama_barang, qty, satuan, id_barang, perkiraan]);

 $.ajax({
    url: '<?= base_url("Admin/Pengadaan/tambahSPB") ?>',
    type: 'POST',
    dataType: 'json',
    data: {
        id_rab: id_rab,
        tgl_order: tgl_order,
        id_supplier: id_supplier,
        kode_supplier: kode_supplier,
        alamat_supplier: alamat_supplier,
        nama_supplier: nama_supplier,
        provinsi_supplier: provinsi_supplier,
        data_barang: data_barang // data barang is multidimensional array
  },
  success: function(data) {
    alert(data.data_barang);
  });

Server side code:

 $data_barang[] = $this->request->getPost("data_barang");
 $dataStatus = [
            "message" => $message,
            "detail" => $data_detail,
            "data_barang" => $data_barang
        ];

 echo json_encode($dataStatus);

I tried to use json.stringifiy on the client side and on server side I use json_decode, but it did not work

CodePudding user response:

convert your array to string with JSON.stringify

data: {
  id_rab: id_rab,
  tgl_order: tgl_order,
  id_supplier: id_supplier,
  kode_supplier: kode_supplier,
  alamat_supplier: alamat_supplier,
  nama_supplier: nama_supplier,
  provinsi_supplier: provinsi_supplier,
  data_barang: JSON.stringify(data_barang) // data barang is multidimensional array
}

you can check array with

$data =  json_decode($_POST['data_barang']);
print_r($data);
  • Related