In this article · 7 sections
AJAX means updating part of a page without reloading it. Modern JavaScript does this with the fetch API. The live search on the Joboo Web blog, instant fare calculators and "submit without reload" forms all work this way. This JavaScript fetch tutorial uses a simple PHP backend.
1. A PHP endpoint that returns JSON
api/fare.php:
<?php
header('Content-Type: application/json');
$km = max(0, (int)($_GET['km'] ?? 0));
$rate = 12;
echo json_encode(['km' => $km, 'fare' => $km * $rate]);
See JSON explained for the format.
2. GET request with fetch
async function getFare(km) {
const res = await fetch('/api/fare.php?km=' + encodeURIComponent(km));
if (!res.ok) throw new Error('Server error ' + res.status);
return res.json();
}
document.querySelector('#km').addEventListener('change', async (e) => {
const out = document.querySelector('#fare');
out.textContent = 'Calculating…';
try {
const data = await getFare(e.target.value);
out.textContent = '₹' + data.fare.toLocaleString('en-IN');
} catch (err) {
out.textContent = 'Could not calculate. Please call us.';
}
});
3. POST a form without reload
const form = document.querySelector('#enquiry');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const res = await fetch('/api/enquiry.php', {
method: 'POST',
body: new FormData(form)
});
const data = await res.json();
form.querySelector('.msg').textContent = data.ok ? 'Thank you! We will call you shortly.' : data.error;
});
In PHP, read the values from $_POST as usual, validate them, and return JSON like {"ok":true}.
4. Live search with debounce
Avoid sending a request on every keystroke; wait until typing pauses:
let timer, controller;
input.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(async () => {
if (controller) controller.abort(); // cancel the previous request
controller = new AbortController();
try {
const res = await fetch('/search-api.php?q=' + encodeURIComponent(input.value), { signal: controller.signal });
render(await res.json());
} catch (e) {
if (e.name !== 'AbortError') console.error(e);
}
}, 200);
});
Good practices
- Show loading and error states
- Insert user-provided text with
textContent, notinnerHTML - Validate on the server too; JavaScript checks can be bypassed. See form validation
- Protect POST endpoints with CSRF tokens if users are logged in
- Use the Network tab in DevTools to inspect requests. See DevTools guide
SEO note
Content loaded only by JavaScript may be indexed later or not at all. Keep important content in the initial HTML. See JavaScript SEO.
FAQs
Is fetch supported in all browsers?
All modern browsers support it.
Is jQuery's $.ajax still needed?
No for new projects; fetch covers the same needs.
Was this article helpful?
Your answer helps us improve our guides