2
5

More than 3 years have passed since last update.

Fetch APIでPOSTしたJSONをPHPで受け取ってエコーするだけ

Last updated at Posted at 2019-11-04

フロントエンドもままならないまま最近PHPに入門して、いろいろ戸惑ったのでメモです。

知見

  • 非同期でやりたいので画面の遷移をキャンセルするためのpreventDefault()をしたいが、これだと<input required>なフォームを未入力のままsubmitしようとした際にフォームに表示されてほしいエラーメッセージが表示されない。これをcheckValidity()で解決
  • fetchでPOSTしても$_POSTで受け取れない。file_get_contents("php://input")で受け取る
  • file_get_contents("php://input")で受け取ってもJSONではなく文字列になってる。json_decode をかませてパースする
  • json_decodeするときは第2引数にtrueしとくとうれしい
  • json_encodeするときは第2引数にJSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHESしとくとうれしい

html

 <form method="POST" enctype=”multipart/form-data” action="" id="registForm">
  <fieldset>
   <label for="name">name</label>
   <input name="name" id="name" type="text" placeholder="" required>
   <button id="registBtn" type="submit">submit</button>
  </fieldset>
 </form>

js

const form = document.getElementById("registForm");
document.getElementById("registBtn").addEventListener("click", (e)=>{
  if(!form.checkValidity()){
    return;
  }
  e.preventDefault();
  e.stopPropagation();
  const name = document.getElementById("name").value;
  fetch("api/regist", {
    method: "POST",
    headers: { "Content-Type": "application/json;charset=utf-8" },
    mode: "cors",
    credentials: "same-origin",
    body: JSON.stringify({
      "name": name,
    }),
  }).then((res)=>{
    return res.json();
  }).then((res)=>{
    console.log(res);
  });
 });

php

POSTをそのまま返すだけじゃつまらんのでサーバー情報も返してます。

api/regist.php
<?php
  $my_POST = json_decode(file_get_contents("php://input"), true);
  $ret = ["post"=>$my_POST, "info"=>$_SERVER]; 
  echo json_encode($ret, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5