LoginSignup
0
0

More than 3 years have passed since last update.

fetch template

Last updated at Posted at 2020-06-19

phpでデータを取ってくる。

変数(parameter)と値(value)をsetDataに渡して、setDataToDB.phpでは例えばPDOでDBにデータをupdate(or insert)する。

setDataToDB.phpがもし戻り値としてデータセットを返す場合にはthen((json)の中で処理する。

fetchSample.js
function setData(paramater, value) {
    var res = fetch("./setDataToDB.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            "value": value
        })
     }).then((response) => {
        if(response.ok)
        return response.json(); // レスポンスをテキストとして変換する
    }).then((json) => {
        //console.log(json[0]["someParameter"]); //複数のデータセットが帰ってくる場合は0でない。
        //何らかの処理;
        return json[0]["otherParameter"]; //returnで返らない?
    });
}

fetchで取ってきた値を他の関数でも使いたい場合にはどうするの?

受信するphp

setDataToDB.php
<?php
$str_json = file_get_contents('php://input');
$json_obj = json_decode($str_json, true);

//データベース接続ーーーーーーーーーーーーーーーー
$dsn = 'mysql:dbname=データベース名;host=localhost';
$user = 'ユーザ名';
$password = 'パスワード';
$dbh = new PDO($dsn, $user, $password);

//SQL処理ーーーーーーーーーーーーーーーーーーーーー
$dbh->beginTransaction();
$stmt = $dbh->prepare("update テーブル名 set カラム名=:mode;");
$stmt->bindParam(':mode', $json_obj["value"], PDO::PARAM_STR);
$stmt->execute();
$dbh->commit();
$result = $stmt->fetchall(PDO::FETCH_ASSOC);

echo $result; //結果
?>
0
0
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
0
0