Reputation: 9537
I would like to send an array I created in my Jquery script to a php file. I know that question has been treated a lot. Unfortunately when applying what seems to be a best practice I do not manage to get it working. Hope someone can help me undertand. Thank you in advance. Cheers. Marc. Here below my code:
my js:
// I build myArray
var myArray = new Array();
$('.someClass').each(function() {
$this = $(this);
myArray.push({
'id': $this.attr('attrId')
});
});
//...and then send it to myFile.php
var ajaxData = { myArray: JSON.stringify(myArray) };
$.ajax({
type: "POST",
url: "myFile.php",
data: ajaxData,
success: function(data) {
$('body').append(data);
}
});
my php:
$myArray = json_decode(stripslashes($_POST['myArray']));
foreach($myArray as $value){
echo $value.'</br>';
}
the error I get:
Catchable fatal error: Object of class stdClass could not be converted to string
Upvotes: 0
Views: 4341
Reputation: 13257
Try replacing this line:
$myArray = json_decode(stripslashes($_POST['myArray']));
With this:
$myArray = json_decode(stripslashes($_POST['myArray']), true);
If the second parameter of json_decode() is set to true, all objects will be converted to associative arrays: http://php.net/manual/en/function.json-decode.php
Upvotes: 3