AJAX JavaScript

AJAX stands for Asynchronous JavaScript and XML. It’s a set of web development techniques that allows web pages to communicate with a server and update parts of the page without reloading the entire page.

Why Use AJAX?

Imagine filling a form, clicking submit, and having the entire page reload. Not very user-friendly, right? AJAX helps solve this by making background server requests and updating only the relevant parts of the web page.

For example:

  • Loading new comments without refreshing the page.
  • Validating a username in real time.
  • Infinite scrolling (like on Facebook or Twitter).

How AJAX Works

AJAX is not a programming language. It’s a technique that uses:

  • JavaScript to send/receive data.
  • XMLHttpRequest or the newer Fetch API.
  • HTML/CSS to display results.

In traditional websites, every server interaction reloads the entire page. With AJAX, data is fetched in the background and only the needed parts of the page are updated.


Basic AJAX with XMLHttpRequest

javascriptCopyEditconst xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);

xhr.onload = function () {
  if (xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    console.log(data);
    document.getElementById('result').innerText = data.title;
  }
};

xhr.send();

Explanation:

  • XMLHttpRequest() creates a new AJAX request object.
  • open('GET', url, true) sets up the request method and URL.
  • onload is triggered when the data is received.
  • send() sends the request to the server.

Modern AJAX with Fetch API

The fetch() function is a more modern way to make AJAX requests:

javascriptCopyEditfetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    document.getElementById('result').innerText = data.title;
  })
  .catch(error => console.error('Error:', error));

Advantages of Fetch:

  • Cleaner syntax.
  • Returns Promises.
  • Easier to chain .then() and .catch().

AJAX POST Request Example

javascriptCopyEditfetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Hello AJAX',
    body: 'This is a POST request example.',
    userId: 1
  })
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));

Use Case:

Sending form data to the server without reloading the page.


Common Use Cases for AJAX

  • Auto-suggestions (like Google search).
  • Real-time chat applications.
  • Dynamic content loading.
  • Form validation.
  • E-commerce filters (price, brand, category).

Simple AJAX Form Example

htmlCopyEdit<form id="myForm">
  <input type="text" name="username" placeholder="Enter username" required>
  <button type="submit">Check</button>
</form>
<div id="response"></div>

<script>
  document.getElementById('myForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const username = e.target.username.value;

    fetch(`https://api.example.com/validate?username=${username}`)
      .then(res => res.json())
      .then(data => {
        document.getElementById('response').innerText = data.message;
      })
      .catch(err => console.error(err));
  });
</script>

Tips When Using AJAX

  • Always handle errors using .catch() or error callbacks.
  • Use JSON.stringify() for sending JSON data.
  • Set appropriate headers (Content-Type) for POST requests.
  • Avoid hardcoding URLs; use variables or configuration files.

Conclusion

AJAX helps you create faster, more dynamic web applications. By updating parts of a page in the background, you enhance the user experience significantly. Whether you use XMLHttpRequest or the Fetch API, learning AJAX is essential for modern web development.

Practice by building mini-projects like:

  • Weather app using an API.
  • Real-time search bar.
  • Comment or chat box.

Once comfortable, you can integrate AJAX with libraries like jQuery, Axios, or frameworks like React or Vue.

Leave a Reply

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