The problem your having is this string is NOT Proper JSON: [500,'hello world']
this would be proper JSON [500,"hello world"]. JSON is very strict on formatting and requires that all string values be wrapped in double quotes and NEVER single quotes.
the proper thing to do to avoid problems, would be to use the php functions json_encode() and json_decode()
for example,
<?php
$myarray[] = 500;
$myarray[] = "hello world";
$myjson = json_encode($myarray);
?>
<form name="input" action="post.php">
<input type="hidden" name="json" value="<?php echo $myjson ?>" />
<input type="submit" value="Submit">
</form>
and in the post.php you would read it like so,
<?php
$posted_data = array();
if (!empty($_POST['json'])) {
$posted_data = json_decode($_POST['json'], true);
}
print_r($posted_data);
?>
the true flag in json_decode() tells the function you want it as an associative array and not a PHP object, which is its default behavior.
the print_r() function will output the php structure of the converted JSON array:
Array(
[0] => 500
[1] => hello world
)
Answer from Sheac on Stack OverflowThe problem your having is this string is NOT Proper JSON: [500,'hello world']
this would be proper JSON [500,"hello world"]. JSON is very strict on formatting and requires that all string values be wrapped in double quotes and NEVER single quotes.
the proper thing to do to avoid problems, would be to use the php functions json_encode() and json_decode()
for example,
<?php
$myarray[] = 500;
$myarray[] = "hello world";
$myjson = json_encode($myarray);
?>
<form name="input" action="post.php">
<input type="hidden" name="json" value="<?php echo $myjson ?>" />
<input type="submit" value="Submit">
</form>
and in the post.php you would read it like so,
<?php
$posted_data = array();
if (!empty($_POST['json'])) {
$posted_data = json_decode($_POST['json'], true);
}
print_r($posted_data);
?>
the true flag in json_decode() tells the function you want it as an associative array and not a PHP object, which is its default behavior.
the print_r() function will output the php structure of the converted JSON array:
Array(
[0] => 500
[1] => hello world
)
Is the API a 3rd party on or made by you?
If it is yours, consume the data sent by your form should be as simple as this on your API:
<?php
$data = json_decode($_REQUEST['json']);
echo $data[0]; // Should output 500
echo $data[1]; // Should output hello world
If it is a 3rd party, probably they expect you to send the json in post body. To accomplish that, follow this post: How to post JSON to PHP with curl.
get POSTed JSON Array in php
jquery - JSON Post and Decode array to PHP - Stack Overflow
Send JSON string (array) from Javascript to PHP via POST - Stack Overflow
send JSON or array to submit POST (jQuery -> PHP)
file_get_contents() does not parse the content. You need to pass the value through json_decode().
<?php
$params = json_decode(file_get_contents("php://input"), true);
echo ($params["key_1"]);
?>
In main.php, use this code:
<?php
$params = json_decode(file_get_contents("php://input"));
echo $params->key_1;
?>
When you decode a JSON string, you convert it to an object of stdClass.
If you want to decode JSON and convert it to an array, use code below:
<?php
$params = json_decode(file_get_contents("php://input"), true);
echo $params['key_1'];
?>
You have to post the data in this format to retrieve like $_POST["arr"]
data: { arr : JSON.stringify(arr) },
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
You should better use POST to pass such type of data, but, absolutely you could make a :
$str = serialize(json_decode($data, true));
And then pass you $str in url.
You can't send the JSON array directly, but you can prepare it in a way that allows it to be sent to your API. You turn your JSON into a string and encode it so it will be properly formatted for a GET.
// your JSON data
var data = '{"name":"Homer Simpson","status":"Suspended","disciplinary-dates":["2018-01-2","2018-02-14","2018-03-17"]}' ;
// take your JSON, turn it into a string and then encode it
var urlParams = encodeURIComponent(JSON.stringify(data)) ;
// your URL adding your JSON data as the value
var url = 'http://example.com/?params=' + urlParams ;
On the PHP side you will decode
// note: this code does not have any error checking - you should add it
// get your params
$params = $_GET['params'] ;
// decode the string
$decodedParams = urldecode($params) ;
// turn your string into an array
$wasJSONAsArray = json_decode($decodedParams, true) ;
// turn your string into a std object
$wasJSONAsStdObj = json_decode($decodedParams) ;
Try this:
$postData = json_decode(file_get_contents("php://input"));
If you simply POST a good old HTML form, the request looks something like this:
POST /page.php HTTP/1.1
key1=value1&key2=value2&key3=value3
But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:
POST /page.php HTTP/1.1
{"key1":"value1","key2":"value2","key3":"value3"}
The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet).
The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).
If your whole POST body contains the JSON, you can get it using thid piece of code:
$json = file_get_contents('php://input');
$decoded = json_decode($json);
This requires you to serialize the javascript array into a string, something that can easily be done using the JSON object.
var myArray = [1, 2, 3];
var myJson = JSON.stringify(myArray); // "[1,2,3]"
....
xhr.send({
data:{
param: myJson
}
});
As the JSON object is not present in older browsers you should include Douglas Crockfords json2 library
If you already rely on some library that includes methods for encoding/serializing then you can use this instead. E.g. ExtJs has Ext.encode
If you're not using a javascript library (jQuery, prototype.js, etc) that will do this for you, you can always use the example code from json.org
$.ajax({
url: "api",
type: "POST",
dataType: 'json',
data: JSON.stringify(arr),
success: function(response){}
});
And with PHP:
$strRequest = file_get_contents('php://input');
$Request = json_decode($strRequest);
I think JSON.stringify() might be useful.
or, you can use json_decode() in php file.