I'm trying to pass an array from javascript to PHP. The error message says:
NULL Warning: Invalid argument supplied for foreach() in /Library/WebServer/Documents/jsontest/json_receive.php on line 10
Anything wrong with my code?
<script>
function sendData(){
var arr= [{
"city" : "Brussels",
"age" : 25
},
{
"city" : "Antwerp",
"age" : 40
}];
$.ajax({
type: "POST",
url: "json_receive.php",
datatype: 'JSON',
data: {arr: JSON.stringify(arr)},
success: function(data){
console.log("success:",data);
},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});
}
<?php
$data = json_decode($_POST["arr"]);
// will echo the JSON.stringified - string:
echo $_POST["arr"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
print_r($data);
foreach($data as $cityObject){
echo "City: " . $cityObject->city . ", Age: " . $cityObject->age . "<br/>";
}
?>