Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax return array shows [object Object],[object Object] in PHP

Within Jquery I am creating two arrays, one embedded in the other, like so....

arrayOne = [{name:'a',value:1}, {name:'b',value:2}]
var arrayTwo = [{name:'foo',value:'blah'},{name:'arrayOne',value:arrayOne}];

I am then putting this though Ajax and extracting the variable via PHP on the other side. The results of a print_r($arrayTwo) are as follows...

Array([foo] => blah [arrayOne] => [object Object],[object Object])

I can see no way of extracting the contents of arrayOne, which is a pity because I really need them! Can anyone tell me what I am doing wrong in Jquery or what I need to do in PHP to make the embedded array accessible.

Many thanks as always


Edit to add my Ajax code....

$.ajax({
  type: "POST",
  url:'actions.php',
  data:arrayTwo,
  datatype:'json',
  cache: false,
  success: function(data){

}

})

like image 891
Jules Avatar asked Nov 18 '15 19:11

Jules


1 Answers

The issue is that jQuery's $.ajax (or rather $.param) method treats an array of objects in a special way. jQuery will use name as the parameter name and the string representation of value as value:

> $.param([{name: 'foo', value: 42}, {name: 'bar', value: 21}])
"foo=42&bar=21"

But the string representation of arrayOne is the useless stuff you are seeing on the server:

> [{name:'a',value:1}, {name:'b',value:2}].toString()
"[object Object],[object Object]"

The documentation actually points out the caveats when passing an array / object:

If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray()

[
  { name: "first", value: "Rick" },
  { name: "last", value: "Astley" },
  { name: "job", value: "Rock Star" }
]

Note: Because some frameworks have limited ability to parse serialized arrays, developers should exercise caution when passing an obj argument that contains objects or arrays nested within another array.

Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.


Since you have a complex data structure, you should probably use JSON to encode your data:

data: {data: JSON.stringify(arrayTwo)},

and on the server you simply decode it with

$data = json_decode($_POST['data'], true);

$data will have the exact same structure as arrayTwo.

But in case you want to actually have parameters with names foo and arrayOne, then you only need to serialize the the value of arrayOne:

data:  [
  {name:'foo',value:'blah'},
  {name:'arrayOne',value: JSON.stringify(arrayOne)}
],

and in PHP:

$arrayOne = json_decode($_POST['arrayOne'], true);
like image 135
Felix Kling Avatar answered Sep 26 '22 17:09

Felix Kling