Estimated reading: 3 minutes 81 views

πŸš€ AJAX Tutorial – Learn How to Make Web Pages Dynamic


πŸ” What is AJAX?

AJAX (Asynchronous JavaScript and XML) enables web pages to communicate with servers behind the scenesβ€”without refreshing. Nowadays, it handles JSON, HTML, plain text, and more.


πŸͺ„ Why Use AJAX?

  • βœ… Create smoother user experiences
  • πŸ”„ Update parts of a page dynamically
  • ⚑ Reduce server load and bandwidth
  • βž• Load data incrementally (infinite scroll, live search)

βš™οΈ Setting Up Your Workspace

  1. Create an index.html and script.js file
  2. Use any text editor (VS Code, Sublime)
  3. Optionally spin up a local server (http-server, Python SimpleHTTPServer) to test requests

πŸ“‘ Basic AJAX with Vanilla JavaScript

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

Key points:

  • open(method, url, async)
  • onreadystatechange and readyState
  • status code checks

🌐 AJAX with Fetch API

Modern, promise-based:

fetch('https://api.example.com/data')
  .then(res => {
    if (!res.ok) throw new Error('Network error');
    return res.json();
  })
  .then(data => console.log(data))
  .catch(err => console.error(err));

Or with async/await:

async function getData() {
  try {
    const res = await fetch('/api/data');
    if (!res.ok) throw new Error('Fetch failed');
    const data = await res.json();
    console.log(data);
  } catch (e) {
    console.error(e);
  }
}

πŸ” Handling JSON Data

Requests return JSON:

fetch('/api/users')
  .then(res => res.json())
  .then(users => {
    users.forEach(u => {
      document.body.insertAdjacentHTML('beforeend', `<p>${u.name}</p>`);
    });
  });

Use JSON.stringify() to send JSON:

fetch('/api/create', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice' })
});

🧩 AJAX in jQuery

$.ajax({
  url: '/api/data',
  method: 'GET',
  dataType: 'json',
  success(data) { console.log(data); },
  error(err) { console.error(err); }
});

Shorter:

$.getJSON('/api/data', data => console.log(data));

πŸ” Error Handling & Timeout

xhr.timeout = 5000;
xhr.ontimeout = () => console.error('Time out');
xhr.onerror = () => console.error('Request error');

Fetch example:

fetch('/api')
  .then(res => res.ok ? res.json() : Promise.reject(res))
  .catch(err => console.error('Error:', err));

πŸ“¦ AJAX Request Types

  • GET: Fetch data
  • POST: Send new data
  • PUT/PATCH: Update resources
  • DELETE: Remove resources
    Set headers and body accordingly.

πŸ“ˆ Real‑World AJAX Use Cases

  • πŸ›’ Live search auto-suggestions
  • πŸ”„ Form submissions without reload
  • πŸ“Š Charts and dashboards updated in real-time
  • 🧡 Infinite scroll on social feeds

πŸ› οΈ Best Practices

  • πŸ§ͺ Use async/await for clarity
  • βœ… Always check res.ok
  • πŸ” Handle timeouts and errors gracefully
  • πŸ”‚ Avoid callback hell
  • πŸ” Secure against XSS, CSRF, CORS issues

🏁 Conclusion

AJAX is the magic behind modern web apps β€” live updates, seamless UX, and smarter data handling. From your first XMLHttpRequest to full-fledged fetch-based patterns, mastering AJAX makes you a frontend wizard. Keep practicing by building chats, maps, and dashboards with live data!


❓ FAQs

Q1: Is AJAX still relevant?
πŸ…°οΈ Absolutely. It powers modern SPAs, real-time features, and micro-interactions.

Q2: Should I use fetch or XMLHttpRequest?
πŸ…°οΈ Use fetch. It’s cleaner, promise-based, and easier to read with async/await.

Q3: How to send POST data with AJAX?
πŸ…°οΈ Include method: 'POST', headers: {'Content-Type': 'application/json'}, and body: JSON.stringify(data) in fetch or XHR.

Q4: Can AJAX call APIs from other domains?
πŸ…°οΈ Yes, if CORS is configured properly on the server.

Q5: How do I test AJAX locally?
πŸ…°οΈ Use a local dev server like http‑server or python -m http.server, because AJAX won’t work with plain file:// URLs.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

AJAX Tutorial

Or Copy Link

CONTENTS
Scroll to Top