I'm trying to send an array from Javascript to PHP.
function wishlist_save(arr){
$.ajax({
type: "POST",
url: "from.php?type=customers",
data: {info: JSON.stringify(arr) },
success: function(){
}
});
}
The array is set this way:
function getAll(){
var info = [];
var i = 0;
$(".desc").each(function(){
var value = $(this).text();
var qtt = $(this).attr('alt');
info[i] = [];
info[i]['desc'] = value;
info[i]['qtt'] = qtt;
i++;
});
return info;
}
If I output (with console.log(getAll())
) the array in javascript I get the right values in Chrome Console:
[Array[0], Array[0], Array[0]]
->0: Array[0]
desc: 'John'
alt: 'Good'
->1: Array[0]
desc: 'Obama'
alt: 'Great'
But in PHP (from.php?type=customers
) I can't figure out how to get those values..
$arr = json_decode($_POST['info']);
ChromePhp::log($arr[0]['desc']); // returns null
What am I doing wrong?
Solved.
The problem was on JSON.stringify(arr)
, which in some way didn't send properly the array to PHP.
So, all I needed was to adapt the function that retrieves the array:
var info = [];
info.push({desc: value, qtt: qtt });
Besides that, the AJAX only now need:
data: {info: arr },
And PHP:
print_r($arr);
what is the output of this? – Awlad Liton Mar 5 at 11:29json_decode($_POST['info'], true)
, or$arr[0]->desc
. – Dave Chen Mar 5 at 11:33ChromePhp::log(print_r($arr));
I receive 'True' in console. @RahulDesai I didn't get your answer..I'm using JSON.. @DaveChen didn't work..retrieves null @PhilipGChromePhp::log($_POST['info']);
retrieves[[],[],[]]
in console. – user3355243 Mar 5 at 11:42