Fetch API POST Requests and JSON Data
Use POST when a request submits data or performs an action. For JSON endpoints, serialize the payload and declare its media type.
Send JSON
const response = await fetch('/api/profile.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ displayName: 'Taylor' })
});
const result = await response.json();
if (!response.ok) throw new Error(result.message || 'Request failed');
Read JSON in PHP
$payload = json_decode(file_get_contents('php://input'), true);
if (!is_array($payload)) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['message' => 'Invalid JSON']);
exit;
}
Validate every expected field on the server, enforce length and type limits, and reject unexpected values. Use prepared statements for database operations.
Response design
Return consistent JSON structures and meaningful status codes. Avoid returning stack traces, SQL errors, or secrets to the browser. State-changing requests also need authentication, authorization, and CSRF protection.