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

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
黃韋智

黃韋智

自學寫程式,目前爲 React 前端工程師。熱愛旅遊,將近 30 個國家,足跡遍佈亞洲與歐洲。生命與街舞已經離不開,歡迎訂閱 Youtube 頻道:https://www.youtube.com/channel/UCEU-bEDl7R-iGyLVZFae33g