JSON Post and Decode array to PHP
Solution 1
You have to post the data in this format to retrieve like $_POST["arr"]
data: { arr : JSON.stringify(arr) },
Solution 2
What the heck are you trying?
It looks as if you are trying to put key-value-pairs to the JavaScript-Array with arr.push('1', 'Brussels|25');
expecting an array containing "Brussels|25" under the key "1" - but watch out, you are creating this array: ["1", "Brussels|25", "2", "Antwerp|40"]
.
If you want to send json, send json-data:
var arr= [{
"city" : "Brussels",
"age" : 25
},{
"city" : "Antwerp",
"age" : 40
}];
then your ajax call:
$.ajax({
type: "POST",
url: "jsondecode.php",
data: {arr: JSON.stringify(arr)},
success: function(data){
console.log("success:",data);},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});
So you don't need to explode the data server-sided.
The server-sided script:
<?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:
foreach($data as $cityObject){
echo "City: " . $cityObject->city . ", Age: " . $cityObject->age . "<br/>";
}
?>
Hope, this helps you now.
@edit: By the way, use console.log()
or console.error()
instead of alert. Alert will cause scripts to pause until you click on ok and you cannot see objects in an alert.
@2nd edit: the script is now tested, I removed unnecessary code and added the server-sided code
Solution 3
Replace :
$array = json_decode($_POST["arr"]);
By:
$array = json_decode($_POST["arr"], true);
Michael V
Updated on June 07, 2022Comments
-
Michael V almost 2 years
I'm tring to post an array to PHP file using JSON. It does not work. The problem is nothing happens. If I decomment datatype:"json" then I get the alert (but without data).
This is my jquery code
var arr = new Array(); arr.push('1','Brussels|25'); arr.push('2','Antwerp|40'); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "jsondecode.php", data: JSON.stringify(arr), dataType: "json", success: function(data){alert(data);}, failure: function(errMsg) { alert(errMsg); } });
And this is my PHP code (jsondecode.php);
<?php $array = json_decode($_POST["arr"]); foreach($array as $el){ $el_array=explode('|',$el); echo"City=".$el_array[0]." And Age = ".$el_array[1].""; } ?>
Does somebody know a useful tutorial on this?