Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 147 ยท PHP and the Web

AJAX, fetch and Progressive Enhancement

Make PHP pages update without a reload: write JSON and HTML-fragment endpoints, call them with fetch, and add the htmx idea on top of working HTML forms.

Every request you have handled so far ended with a whole new page. The browser submitted a form, PHP built HTML and the browser replaced everything on screen. That is simple and robust, but it feels heavy when you only want to add one item to a list, tick a checkbox or check whether a username is free.

AJAX (Asynchronous JavaScript and XML, though today it carries JSON or HTML far more often than XML) means that JavaScript sends a request in the background and updates part of the page with the answer. PHP's side of the story is pleasantly small: an endpoint is just a script that returns data or a snippet of HTML instead of a full page. In this lesson you will write both kinds of endpoint, call them with the browser's fetch() function and learn the idea behind htmx, a library that lets plain HTML attributes do the same job. Throughout, you will keep the golden rule of progressive enhancement: the page must still work without JavaScript.

If you need a refresher first, see Building a JSON API, Forms and HTTP Headers, Status Codes and Redirects.

The shape of an AJAX interaction

sequenceDiagram
  participant B as Browser (JavaScript)
  participant P as PHP endpoint
  B->>P: fetch("/api/users/check?name=ada")
  P-->>B: 200 {"available": false}
  B->>B: Update one element on the page
  Note over B,P: No page reload, only the changed part is transferred

JavaScript sends the request, PHP replies with data, and JavaScript patches the page.

Two styles dominate:

  1. JSON endpoints. PHP returns data; JavaScript decides how to draw it. This is the right fit for rich front ends and mobile apps.
  2. HTML-fragment endpoints. PHP returns ready-made HTML for the part of the page that changes, and JavaScript just swaps it in. This keeps your templates and escaping logic in PHP and needs very little JavaScript. It is the approach htmx uses.

A JSON endpoint

A JSON endpoint reads input, validates it, and answers with a status code and a JSON body. Because the editor can't serve HTTP, the handler below takes the query array and returns the response, so you can see exactly what a browser would receive:

PHP A JSON endpoint: is the username free?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In a real script the last lines would be http_response_code($status); header('Content-Type: application/json'); echo json_encode($body);. Notice the status codes: 422 for bad input and 200 for a valid question, whatever the answer is. "Not available" is a normal result, not an error.

Calling it with fetch

fetch() returns a promise. The usual pattern is await fetch(...), check response.ok, then await response.json(). Here is the client for the endpoint above. It is read-only because it needs a real server:

HTML
<label>
  Username
  <input id="username" name="username" autocomplete="off">
</label>
<p id="username-hint" aria-live="polite"></p>

<script>
  const input = document.querySelector('#username');
  const hint = document.querySelector('#username-hint');
  let timer;

  input.addEventListener('input', () => {
    clearTimeout(timer);                       // debounce: wait until typing pauses
    timer = setTimeout(checkName, 300);
  });

  async function checkName() {
    const url = '/api/username-check?name=' + encodeURIComponent(input.value);
    try {
      const response = await fetch(url, { headers: { Accept: 'application/json' } });
      const data = await response.json();
      hint.textContent = response.ok
        ? (data.available ? 'Available' : 'Already taken')
        : data.error;
    } catch (error) {
      hint.textContent = 'Could not reach the server';
    }
  }
</script>

Three details matter. encodeURIComponent() makes the user's text safe inside a URL. aria-live="polite" makes screen readers announce the message when it changes. And fetch() only rejects its promise on network failure: a 404 or 500 still resolves, so you must check response.ok yourself.

Sending data to PHP

For writes, send a POST with either form encoding or JSON. With a FormData object, the browser sends an ordinary form submission and PHP fills $_POST as always:

JavaScript
const form = document.querySelector('#comment-form');
const body = new FormData(form);              // includes every named field
const response = await fetch(form.action, { method: 'POST', body });

With JSON, set the header and stringify the object. PHP then has to read the raw body, because $_POST stays empty:

JavaScript
await fetch('/api/comments', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ text: 'Nice post!' }),
});
PHP
<?php
$data = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);

AJAX does not change the security rules. A request sent by fetch() is a normal HTTP request, so validate every field on the server, escape output (see XSS and Output Escaping) and protect state-changing requests against CSRF, for example by sending the token in a header or in the form data.

An HTML-fragment endpoint

Instead of returning data, the endpoint can return the finished HTML for the changed region. The big advantage is that all rendering, translation and escaping stays in PHP. The next demo renders a comment list item. Pay attention to htmlspecialchars(): a fragment endpoint produces HTML, so escaping is its job:

PHP An HTML-fragment endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The attacker's <script> tag comes back as harmless text. On the client the swap is a one-liner such as list.insertAdjacentHTML('beforeend', await response.text()). Because the server returns HTML, never insert it with data from other origins, and never build such HTML with unescaped user input.

Progressive enhancement

JavaScript can fail: a script error, a slow connection, an ad blocker, a corporate proxy or a crawler. A robust site therefore works in layers:

  1. A normal <form method="post" action="/comments"> that works with no JavaScript and redirects back (the post/redirect/get pattern).
  2. JavaScript that intercepts the submit event, sends the same data with fetch() and updates the page in place.
  3. If the fetch fails, fall back to a normal submission.

On the server, one endpoint can serve both layers. It checks whether the request came from AJAX. There is no official flag, so the convention is a custom header that your JavaScript adds:

PHP One endpoint for full pages and fragments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The client side of layer 2 is short:

JavaScript
document.querySelector('#subscribe-form').addEventListener('submit', async (event) => {
  event.preventDefault();                       // stop the full-page submit
  const form = event.currentTarget;
  const response = await fetch(form.action, {
    method: 'POST',
    headers: { 'X-Requested-With': 'fetch' },
    body: new FormData(form),
  });
  document.querySelector('#subscribe-result').innerHTML = await response.text();
});

Because the markup is a real form, search engines, assistive technology and users without JavaScript all keep working.

The htmx idea

Writing the handler above for every form gets repetitive. htmx is a small JavaScript library that moves it into HTML attributes. You declare what to request, when and where to put the answer, and htmx does the fetch and the swap:

HTML
<script src="https://unpkg.com/[email protected]"></script>

<form hx-post="/subscribe" hx-target="#subscribe-result" hx-swap="innerHTML">
  <input type="email" name="email" required>
  <button>Subscribe</button>
</form>
<div id="subscribe-result"></div>

On submit, htmx sends the form with a HX-Request: true header and puts the response HTML into #subscribe-result. Other common attributes:

Attribute Purpose
hx-get, hx-post, hx-put, hx-delete Which request to send
hx-trigger The event that starts it (click, keyup changed delay:300ms, every 5s)
hx-target Which element receives the response (CSS selector)
hx-swap How to insert it (innerHTML, outerHTML, beforeend, โ€ฆ)
hx-boost Turn ordinary links and forms into AJAX requests automatically

Your PHP code needs almost no change: check for the HX-Request header and return a fragment instead of a full layout. The script URL is shown only as an example; pin versions, and for production consider serving the file from your own domain.

PHP
<?php
$isHtmx = ($_SERVER['HTTP_HX_REQUEST'] ?? '') === 'true';

if ($isHtmx) {
    require __DIR__ . '/fragments/subscribe-result.php';   // just the <p>
} else {
    require __DIR__ . '/pages/subscribed.php';             // the full page
}

Other libraries share the idea, among them Alpine AJAX and Hotwire/Turbo. The principle is the same: the server sends HTML, the browser swaps it in. htmx is not required reading for PHP, but it shows how far you can get with server-side rendering and a few attributes.

Seeing the swap in the browser

The sandbox that runs this page's editors cannot reach a PHP server, so the demo below replaces fetch with a local stand-in that "answers" like the subscribe endpoint. The wiring of event, request and swap is exactly what you would write for a real server:

Intercept a form and swap in a fragment

Change the address to something invalid and submit again to see the error fragment replace the success message.

Practical tips

  • Use the right method. GET for reading, POST/PUT/DELETE for changing. Never change data on a GET.
  • Status codes drive behavior. Return 4xx/5xx for errors, so the client can tell failure from success.
  • Keep URLs real. Give every important view a normal URL that renders a full page, so links, bookmarks and the back button work.
  • Handle loading and failure states. Disable the button while a request is in flight and show a message when it fails.
  • Don't over-engineer. Many pages need no AJAX at all. Add it where the page reload really hurts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A fetch() call receives a 500 response from your PHP script. What happens to the promise?

    fetch only rejects on network-level failure. HTTP error statuses resolve normally, so check response.ok or response.status.
  2. 2. Why does an HTML-fragment endpoint have to call htmlspecialchars() on user text?

    The server builds markup. Any user-supplied text placed into it must be escaped, exactly as in a full page.
  3. 3. What does progressive enhancement mean for an AJAX form?

    The baseline (a real form posting to a real URL) always works; JavaScript adds in-place updates on top.
  4. 4. Which htmx attribute chooses the element that receives the server's HTML response?

    hx-target takes a CSS selector for the destination element; hx-swap controls how the content is inserted there.
  5. 5. A client sends JSON with Content-Type: application/json. Where does PHP find the data?

    PHP only fills $_POST for form encodings, so JSON bodies must be read from php://input and decoded.

Summary

  • AJAX means JavaScript requests data in the background and updates part of the page; PHP only needs endpoints that return JSON or HTML fragments.
  • Use fetch() with await, check response.ok, encode URL parameters with encodeURIComponent() and read JSON bodies from php://input.
  • Fragment endpoints keep rendering and escaping in PHP; always escape user text with htmlspecialchars().
  • AJAX requests need the same validation, escaping and CSRF protection as any other request.
  • Progressive enhancement: build a working form first, intercept it with JavaScript, and let one endpoint answer both modes.
  • htmx expresses the "request, target, swap" pattern in HTML attributes; PHP detects it with the HX-Request header.

Next: Templating: Twig and Blade Concepts