1

I want to sent some data to a php script with the use of redux and promise as if the following.

export function fetchFileContent() {
    return {
        type: "FETCH_FILECONTENT",
        payload: axios.post("/api/ide/read-file.php", {
            filePath: document.getArgByIndex(0)[0]
        })
    };
}

But the php script cannot receive the data. When I print all the data in $_POST using var_dump. There is nothing inside.

I checked the Request Payload in the Google Chrome debugging tool and it seems no problem. enter image description here

In my php script:

if (isset($_POST["filePath"])) 
    echo "yes"; 
else 
    echo "no";
echo "I am the correct file";
var_dump($_POST["filePath"]);

$dir = $_POST['filePath'];
echo $_POST['filePath'];

And I got this response:

noI am the correct file<br />
<b>Notice</b>:  Undefined index: filePath in <b>/var/www/html/api/ide/read-file.php</b> on line <b>7</b><br />
NULL
<br />
<b>Notice</b>:  Undefined index: filePath in <b>/var/www/html/api/ide/read-file.php</b> on line <b>9</b><br />
<br />
<b>Notice</b>:  Undefined index: filePath in <b>/var/www/html/api/ide/read-file.php</b> on line <b>10</b><br />

How can I get back the data in the php script?

Casper
  • 4,435
  • 10
  • 41
  • 72
  • Are you definitely checking the right php file? If you're seeing it being sent in your network tab then there isn't any reason it shouldn't be sending. – Rwd Dec 28 '16 at 19:28
  • @RossWilson - If I modify the script like adding `if (isset($_POST["filePath"])) echo "yes"; else echo "no";`, I can see `no`. If I add `echo "I am the correct file";`, I can also see it in the response. – Casper Dec 28 '16 at 19:31
  • When you do `var_dump($_POST);`, what do you see? It looks like axios is sending a JSON object, so you might need to run json_decode on your $_POST array. – Chris Forrence Dec 28 '16 at 19:41
  • @ChrisForrence - When I do `var_dump($_POST)`, I got `array(0) {}`. – Casper Dec 28 '16 at 19:44
  • 3
    If its JSON you need to get it from php://input like so: `$_POST = json_decode(file_get_contents('php://input'), true);` – Matt Altepeter Dec 28 '16 at 19:50
  • @MattAltepeter - You are correct! Thank you! – Casper Dec 29 '16 at 18:42

1 Answers1

10

Thank to Matt Altepeter and his comment, I finally solved by adding the line:

$_POST = json_decode(file_get_contents('php://input'), true);

So if I do a var_dump($_POST) now, I can get the data filePath.

array(1) {
  ["filePath"]=>
  string(10) "/I am here"
}
Casper
  • 4,435
  • 10
  • 41
  • 72