Home > Mobile >  $_POST variable is empty after fetch request
$_POST variable is empty after fetch request

Time:04-09

In react i write

useEffect(() => {
    fetch("https://ozencalc.ru", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        action: "operations-update"
      })
    })
      .then((res) => {
        return res.json();
      })
      .then((res) => alert(res));
  }, []);

so i'm sending an object as a body and expect to read it on php server where i write

echo json_encode($_POST);

but i get an empty array instead of object with key "action"

What can be the cause that php server variable $_POST doesn't content value

[
  "action" => "operations-update"
]

can it be some hosting server problem or i misunderstood how php works?

CodePudding user response:

Your $_POST will be empty because data was sent in body, try:

$data = json_decode(file_get_contents('php://input'), true);
  •  Tags:  
  • php
  • Related