JS AJAX

AJAX allows asynchronous data loading without refreshing the page. Learn how to fetch data dynamically.

On this page

AJAX Intro

AJAX (Asynchronous JavaScript and XML) means sending and receiving data from a server without reloading the whole page. Today, JSON + Fetch is the most common approach, but you will still see XMLHttpRequest (XHR) in legacy code.

AJAX XMLHttp

XMLHttpRequest is the classic AJAX API. It is callback-based and more verbose than Fetch.

function loadWithXHR(url, onSuccess, onError) {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);

  xhr.onload = function () {
    if (xhr.status >= 200 && xhr.status < 300) {
      onSuccess(xhr.responseText);
    } else {
      onError("HTTP " + xhr.status);
    }
  };

  xhr.onerror = function () {
    onError("Network error");
  };

  xhr.send();
}

loadWithXHR("/api/data",
  (text) => console.log(text),
  (err) => console.error(err)
);

AJAX Request

AJAX requests can be GET (read) or POST/PUT/PATCH/DELETE (write). Modern code typically uses Fetch.

async function getJson(url) {
  const res = await fetch(url);

  if (!res.ok) {
    throw new Error("HTTP error: " + res.status);
  }

  return res.json();
}

getJson("/api/items")
  .then(data => console.log(data))
  .catch(err => console.error(err));

POST JSON request:

async function postJson(url, payload) {
  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload)
  });

  if (!res.ok) throw new Error("HTTP error: " + res.status);
  return res.json();
}

postJson("/api/items", { title: "New" })
  .then(data => console.log(data))
  .catch(console.error);

AJAX Response

A response can be plain text, JSON, or other formats. With Fetch, use the correct parser:

  • res.text() for text
  • res.json() for JSON
  • res.blob() for files
async function loadText() {
  const res = await fetch("/api/version");
  const text = await res.text();
  console.log(text);
}

Always handle HTTP errors:

async function safeFetch(url) {
  const res = await fetch(url);
  if (!res.ok) {
    const msg = await res.text().catch(() => "");
    throw new Error("Request failed: " + res.status + " " + msg);
  }
  return res;
}

AJAX XML File

Historically, AJAX often used XML. Today JSON is more common, but XML still exists in some systems.

function loadXML(url) {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url);

  xhr.onload = () => {
    if (xhr.status === 200) {
      const xml = xhr.responseXML;
      console.log(xml);
    }
  };

  xhr.send();
}

loadXML("/data.xml");

AJAX PHP

AJAX is often used with PHP backends. A common pattern is returning JSON.

// fetch from JS
fetch("/api/user.php?id=1")
  .then(r => r.json())
  .then(data => console.log(data));
<?php
// api/user.php (example)
header('Content-Type: application/json; charset=utf-8');

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Normally you would query the database here
echo json_encode([
  'id' => $id,
  'name' => 'Ozan'
]);

AJAX ASP

AJAX works with any server technology (ASP.NET, Node.js, Python, etc.). The idea is the same: request data, receive data (often JSON), update UI without full reload.

AJAX Database

A typical flow: JavaScript sends request → PHP reads parameters → queries DB → returns JSON → JavaScript updates DOM.

async function loadUsers() {
  const res = await fetch("/api/users.php");
  const users = await res.json();

  const list = document.querySelector("#users");
  list.innerHTML = "";

  for (const u of users) {
    const li = document.createElement("li");
    li.textContent = u.name;
    list.appendChild(li);
  }
}

AJAX Applications

Common real-world AJAX use cases:

  • Live search
  • Auto-save forms
  • Pagination without reload
  • Load more / infinite scroll
  • Dashboards

AJAX Examples

Example: Live search with debounce (modern pattern).

function debounce(fn, delay) {
  let t;
  return (...args) => {
    clearTimeout(t);
    t = setTimeout(() => fn(...args), delay);
  };
}

const input = document.querySelector("#q");
const results = document.querySelector("#results");

const search = debounce(async () => {
  const q = input.value.trim();
  if (!q) {
    results.innerHTML = "";
    return;
  }

  const res = await fetch("/api/search.php?q=" + encodeURIComponent(q));
  const data = await res.json();

  results.innerHTML = data.map(x => `<div>${x.title}</div>`).join("");
}, 300);

input.addEventListener("input", search);

Next Step

Continue with JS JSON to understand JSON parsing, stringifying, and safe data exchange.

JS AJAX Examples (8)