Send asynchronous browser requests with fetch, XMLHttpRequest, JSON, errors, and progressive UI.
Lessons
Send and receive JSON from a PHP endpoint.
AJAX with a PHP Backend is easiest to learn by reading the example, changing it, and observing the result.
// Client
const res = await fetch('/api.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'AJAX + PHP' })
});
console.log(await res.json());
/* Server: api.php
<?php
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);
echo json_encode(['ok' => true, 'title' => $input['title']]);
*/Practice the AJAX with a PHP Backend example in a small scratch file, then explain what changed and why.