PHP 使用Fetch API POST JSON資料,Transaction交易為例

Gary Huang
Dublin so code
Published in
1 min readMar 5, 2019

Javascript 部分

fetch('./purchase.php', { 
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'product_id': 1,
'order_amount': 2,
})
}).then(response => response.text()).then((body) => {
console.log(body);
});

PHP 部分

$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
$product_id = $decoded['product_id'];
$order_amount = $decoded['order_amount'];
$conn->autocommit(FALSE);
$conn->begin_transaction();
$result = $conn->query('SELECT amount FROM products WHERE id = $product_id for update');
$row = $result1->fetch_assoc();
// 確定庫存大於購買數目
if ($row['amount'] >= $order_amount) {
$conn->query("UPDATE products SET amount = amount - $order_amount WHERE id = $product_id");
echo '購買成功'; // echo 回傳值會出現在 JS 中的 then(response)
} else {
echo '購買失敗';
}
$conn->commit();
$conn->close();

參考資料:https://codepen.io/dericksozo/post/fetch-api-json-php

--

--

Gary Huang
Dublin so code

Self-taught in programming, currently working as a web developer and also a online course instructor, helping self-taught programmers find employment.