Skip to content

Instantly share code, notes, and snippets.

@kobitoDevelopment
Last active October 15, 2025 17:26
Show Gist options
  • Select an option

  • Save kobitoDevelopment/17846f5d10ee0c41bfce3f2c7ba420fe to your computer and use it in GitHub Desktop.

Select an option

Save kobitoDevelopment/17846f5d10ee0c41bfce3f2c7ba420fe to your computer and use it in GitHub Desktop.
<?php
// Content-Type: application/json を明示
header('Content-Type: application/json');
// JSONデータを受け取る
$input = json_decode(file_get_contents('php://input'), true);
$productId = $input['productId'] ?? null;
$quantity = $input['quantity'] ?? 0;
// バックエンド側でバリデーションを実施しない例
echo json_encode([
'success' => true,
'message' => "{$quantity}個の商品({$productId})を購入しました!"
]);
<form id="purchase-form">
<label>
個数(最大2個まで):
<input type="number" id="quantity" name="quantity" min="1" max="2" required />
</label>
<button type="submit">購入</button>
</form>
<script>
document.getElementById("purchase-form").addEventListener("submit", async (e) => {
e.preventDefault();
const quantity = parseInt(document.getElementById("quantity").value, 10);
// フロント側バリデーション
if (quantity > 2) {
alert("2個までしか購入できません");
return;
}
// APIに送信
const res = await fetch("api.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ productId: 123, quantity }),
});
const data = await res.json();
alert(data.message);
});
</script>
/* consoleで以下を実行するとリクエストできてしまう */
fetch('http://localhost:8080/api.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId: 123, quantity: 10 })
})
.then(res => res.json())
.then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment