Reputation: 95
I am using postman to post data to very small php script. When I am trying to dump $_POST, its having some data but it gives me error when I am trying to access the variable in $_POST.
PHP Script
<?php
header("Access-Control-Allow-Origin: *");
var_dump($_POST);
$txt = $_POST['result'];
?>
Raw Input in Postman
{"result":"sfd"}
Output
array(1) { ["{"result":"sfd"} "]=> string(0) "" }
Notice: Undefined index: result in C:\xampp\htdocs\apis\index.php on line 4
Whats happening here?
Upvotes: 2
Views: 3466
Reputation: 1352
You are getting a JSON string in arrey it can't be accessed like that first you have to decode it
like
as Array
$result = json_decode($_POST, true)
$txt = $result['result']; // text
as Object
$result = json_decode($_POST)
$txt = $result->result; // text
suggestion
if your making request through jQuery ajax
, i think you are using JSON.stringify()
OR similar method to convert to string so instead of using JSON.stringify()
just post as it is. so in this case you no need to using json_decode()
.
For example
var data = {"result":"sfd"};
// data = JSON.stringify(data); // don't use this
$.ajax({
url : url,
data : data,
...
});
Upvotes: 2
Reputation: 1836
The answer is in a json format, you need to decode it in order to access to this index.
<?php
header("Access-Control-Allow-Origin: *");
var_dump($_POST);
$result = json_decode($_POST, true)
$txt = $result['result'];
?>
Upvotes: 0
Reputation: 6887
use isset function check
<?php
header("Access-Control-Allow-Origin: *");
if(isset($_POST['result'])){
$txt = $_POST['result'];
}
?>
Upvotes: -1