NARUMASA CREATIVE DESIGN
Copyright © narumasa.com
All rights reserved.

Fetch API

APIからデータを取得(get / post)
PHPでAPIを作るにはパラメータ($_GET)ver
APIでのinsertはこちら

Javaacriptで使える非同期 Fetch API。
AjaxやReact.jsを使用しなくても非同期でAPIからデータを取得して表示できる。
JavascriptなのでもちろんjQueryも交えて使うことができる。

WordPressでももちろん使用可能。
WordPressだとwp-ajaxがあるが、正直Fetch APIを使用したほうが手軽でコードもわかりやすく簡単。

例えばフォームのvalueを元にボタン(.getApiBtn)をクリックするとデータを取得できるようにしたい場合、
.formBox・・・入力フォーム(名前[name]・年齢[age]・性別[sex])
.getBtn・・・APIを起動するボタン
.getApiBlock・・・APIから取得したデータを表示するdiv枠

// エンドポイント
http://localhost/member_book/get_api.php

JavascriptでAPIからデータを取得

例)get_api.js

今回はAPIエンドポイントのパラメータを使用してデータをAPIに送ってjsonでresponse取得。
functionでまとめることでコードを見やすくわけてみたバージョン。

・try/catchでエラー処理対応
・awaitで上から順に処理を行うように指定
・empty()を使用しているのは.getApiBlockに「Loading…」などを入れておく
・複数responseがある想定なのでappendで追加
・forEachでループさせ、itemキーで取得して表示

例)get_api.js ※上と同じ

$(document).on('click', '.getApiBtn', function(){
  const name = $('.formBox [name="name"]').val();
  const age = $('.formBox [name="age"]').val();
  const sex = $('.formBox [name="sex"]').val();
  
  fetchData(name, age, sex);   // ここでAPI起動部分を呼び出している
});

// ここからがAPI部分
async function fetchData(name, age, sex)){
  try{
    const response = await fetch(`http://localhost/member_book/get_api.php?name=${name}&age=${age}&sex=${sex}`);
    if(!response.ok){
      throw new Error('fetch was not ok');
    }
    const data = await response.json();
    
    $('.getApiBlock').show();
    $('.getApiBlock').empty();

    data.forEach(item => {
      $('.getApiBlock').append(`
        <div>
          <p>${item.name}(${item.sex})${item.age}歳</p>
        </div>`);
    });
  } catch(error){
    console.error('Fetch error:', error);
  }
}

もう一つの方法としては、thenを使用する方法もある。こちらではGETではなくPOSTで取得するようにしたバージョン。
どちらの方法もありだが、コードのわかりやすさとしてはthenを使用した方法のほうがわかりやすい気がする。
ただ、functionでまとめて外でも使用しやすいという場合はfunctionバージョンがおすすめ。

例)get_api.js

$(document).on('click', '.submitBtn', function(){
  const name = $('.formBox [name="name"]').val();
  const age = $('.formBox [name="age"]').val();
  const sex = $('.formBox [name="sex"]').val();

  const data = {
    name: name,
    age: age,
    sex: sex
  };

  fetch('http://localhost/member_book/get_api.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
  .then(response => {
    if(response.ok){
      alert('insert 完了');
    } else{
      alert('insert 失敗');
    }
  })
  .catch(error => {
    alert('error:' + error.message);
  });
});

ついでにPHPでAPIを作るには、まずパラメータ($_GET)でデータ取得。

例)get_api.php

// DB接続
try{
	$db = new PDO('mysql:dbname=db_name;host=localhost;charset-utf8','id','password');
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
	echo '接続エラー:' . $e->getMessage();
	exit;
}

// get data
$name = !empty($_GET['name']) ? $_GET['name'] : null;
$age = !empty($_GET['age']) ? $_GET['age'] : null;
$sex = !empty($_GET['sex']) ? $_GET['sex'] : null;

$sql = "SELECT *
FROM table_name
WHERE
  name = $name
ORDER BY
  age ASC
";

$result = $db->query($sql);

// データが存在しない場合
if($result === false){
  echo json_encode(["error" => "Table not found"]);
  exit;
}

// データをJSON形式で返す
$data = [];
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
  $data[] = $row;
}

echo json_encode($data);

APIでのinsertは下記を参照。

例)insert_api.php

// DB接続
try{
	$db = new PDO('mysql:dbname=db_name;host=localhost;charset-utf8','id','password');
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
	echo '接続エラー:' . $e->getMessage();
	exit;
}

// get data
$name = !empty($_GET['name']) ? $_GET['name'] : null;
$age = !empty($_GET['age']) ? $_GET['age'] : null;
$sex = !empty($_GET['sex']) ? $_GET['sex'] : null;

// SQL文を準備
$sql = "INSERT INTO table_name (name, age, sex) VALUES (:name, :age, :sex)";

$result = $db->query($sql);

// SQLの実行準備
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':age', $age);
$stmt->bindParam(':sex', $sex);

// データが存在しない場合
if($result === false){
  echo json_encode(["error" => "Table not found"]);
  exit;
}

// SQL実行
try{
  $stmt->execute();
  echo json_encode(["status" => "success", "message" => "insert was success."]);
} catch (PDOException $e){
  echo json_encode(["status" => "error", "message" => "insert was failed: " . $e->getMessage()]);
}
WordPressの自作のカスタムブロックを作る

Warning: Attempt to read property "ID" on string in /home/users/1/craft-work/web/narumasa/wp-content/themes/narumasa/single.php on line 56