LoginSignup
7
8

More than 3 years have passed since last update.

Fetch APIでPHPにデータを送信する方法

Last updated at Posted at 2020-06-24

画面遷移をせず、ajaxでデータをPHPに渡す方法です。

下記は「ボタンをクリックした時にPHPにデータを渡す」処理についてのサンプルです。

Javascript

id="start"のボタンがあるとします。

index.html
<div class="Container">
   <button class="btn" id="start">start</button>
</div>

vanilla Javascriptでは、下記のように記述します。

main.js
start.addEventListener('click', () => {
        const postData = new FormData; // フォーム方式で送る場合
        postData.set('firstName', 'hoge'); // set()で格納する
        postData.set('lastName', 'fuga');

        const data = {
          method: 'POST',
          body: postData
        };

        fetch('test.php', data)
          .then((res) => res.text())
          .then(console.log);
    });

PHP

PHP側で、$_POST連想配列に値が保存されます。

test.php
<?php
echo $_POST['firstName']; // hoge

未対応の古いブラウザでもPolyfillを使用することで、従来のXMLHttpRequestを使った処理をfetchに置き換えることができます。

jQuery

ちなみにjQUeryにもajaxPOSTできる構文があります。

test.js
 $.post( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
 });

プロジェクトによってはこちらを使用する事もあるかもしれません。

参考

github/fetch
MDN/Fetch API
MDN/Promise
jQuery.post()

7
8
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
7
8