If you want to use the Fetch API to send and receive JSON to your PHP script there are a few things you have to take into account.

Javascript

    fetch("/", {
    method: "POST",
    mode: "same-origin",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      "payload": myObj
    })
  })

By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

That really threw me off at first and I was wondering why my requests were not authenticated, but having the propery credentials: 'same-origin' took care of that.

That's about all you need from the Javascript side of things.

PHP

You can't access JSON by default in PHP with the $_POST variable so you have to do a bit of trickery to get access to it.

  $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';

if ($contentType === "application/json") {
  //Receive the RAW post data.
  $content = trim(file_get_contents("php://input"));

  $decoded = json_decode($content, true);

  //If json_decode failed, the JSON is invalid.
  if(! is_array($decoded)) {

  } else {
    // Send error back to user.
  }
}

That's about it. With that you should now be able to send and receive JSON via the Fetch API with your PHP.


1,859 0 17