halococ
halococ

Reputation: 41

get error when json_decode string from ajax post

I try send string to controller, the string is json format, when send to controller, i get error and can't decode my json string in that controller. I try to encode first in my controller, but still get error. And the error is

"json_decode() expects parameter 1 to be string, array given", exception: "ErrorException",

here in my json string

"{ "data" : 
[{
"id": "TNI01",
 "jenis_bayar": "TUNAI",
"no_kartu": "kosong",
"nominal": "10000",
"seq": "1"
} , 
{
"id": "DEB01",
"jenis_bayar": "DEBIT BCA",
"no_kartu": "786382432432",
"nominal": "20000",
"seq": "2"
}]
}"

here the controller

public function ArrayPostToTablePembayaran(Request $request)
    {

       $data = json_decode($request->datajson, true);

       foreach ($data->data as $datas) 
       {
          $id         = $datas->id;
          $jenisbayar = $datas->jenis_bayar;
          $nokartu    = "";

          if($datas->no_kartu == "kosong")
          {
              $nokartu ="";
          }

          $nominal    = $datas->nominal;
          $seq        = $data->seq;
          $this->PosToTablePembayaran1($id , $jenisbayar , $nokartu , $nominal , $seq); 
       }
    }

and here the ajax script for parse json string to controller

function PembayaranKeDatabase1(arraystring)
            {
              $.ajax(
                  {
                      type    : "POST",
                      url     : "{{ url('/trx_bayar') }}",
                      data    : { datajson : JSON.parse(arraydata) } ,
                      dataType: "json",
                      success: function(data){

                      },
                      error: function() {

                      }
                  });
            }

thanks before

Upvotes: 1

Views: 455

Answers (1)

u_mulder
u_mulder

Reputation: 54841

The main issue in your code that you try to decode json twice: in client js code and on server.

Let's inspect what you do:

JS function PembayaranKeDatabase1(arraystring) has an argument of type string, I presume. I also presume that arraystring is a JSON-string. So, you decode JSON-string to object with

JSON.parse(arraydata)  
// btw shouldn't it be 
//JSON.parse(arraystring)

So, here you send some plain object to server, not json.

Next, on server you try to decode again. But you receive an array in $request->datajson, as json is already decoded on client-side.

So, you can choose between two options:

  1. Remove JSON.parse:

    data    : { datajson : arraydata },
    

and use json_decode on server.

  1. Remove json_decode($request->datajson, true) on server. Iterate over your data as

    // as $request->datajson is an array
    foreach ($request->datajson['data'] as $datas) {
        // use [] notation as you work with array, not object
        echo $datas['id'];
    }
    

Upvotes: 1

Related Questions