🌙
Happy Karwa Chauth! Wishing all couples a blessed Karwa Chauth. May your bond grow stronger every year. From Team Job...
💬 Share
Web Development Tutorials

JavaScript Fetch and AJAX Tutorial: Load Data Without Reloading the Page

Live search, instant fare quotes and forms that submit without reloading all use AJAX. Here's a practical JavaScript fetch tutorial with a PHP backend.

In this article · 7 sections
  1. 1. A PHP endpoint that returns JSON
  2. 2. GET request with fetch
  3. 3. POST a form without reload
  4. 4. Live search with debounce
  5. Good practices
  6. SEO note
  7. FAQs
  8. Is fetch supported in all browsers?
  9. Is jQuery's $.ajax still needed?

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, not innerHTML
  • 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

Share this article

Joboo Web

Web design, SEO & digital marketing team · Ludhiana, Punjab

Joboo Web has helped Indian businesses grow online since 2019 — building fast websites and running SEO, Google Ads and social campaigns for clients in 80+ cities. About us →

Keep reading

💬