Sobes.tech
Junior

What is AJAX and how is this technology fundamentally structured?

sobes.tech AI

Answer from AI

AJAX (Asynchronous JavaScript and XML) is a technology that allows web pages to exchange data with the server asynchronously without reloading the entire page.

Principle of AJAX operation:

  1. Browser event: User performs an action (e.g., click a button) or another event triggers an AJAX request.
  2. XMLHttpRequest object (or fetch API): JavaScript creates an XMLHttpRequest object (or uses the modern fetch API) responsible for sending the request.
  3. Sending request: The object sends an HTTP request (usually GET or POST) to the server.
  4. Server processing: The server receives the request, processes it (e.g., fetches data from a database), and forms a response. The response format can be XML, JSON, HTML, or plain text. JSON is most common.
  5. Receiving response: The XMLHttpRequest (or fetch API) receives the server response.
  6. Client-side processing: JavaScript processes the received response.
  7. DOM update: JavaScript dynamically updates the webpage content (DOM) based on the received data, without a full page reload.

Key advantages:

  • Async: Operations are performed asynchronously, not blocking user interaction.
  • Dynamic: Allows updating parts of the page without full reload.
  • Performance: Reduces data transfer volume and speeds up web app operation.

Example using XMLHttpRequest:

// Create XMLHttpRequest object
let xhr = new XMLHttpRequest();
// Open request (method, URL, async? )
xhr.open('GET', '/api/data', true);
// Set callback for when request completes
xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 300) {
    // Data received successfully
    let data = JSON.parse(xhr.responseText);
    // Update DOM or process data
    console.log(data);
  } else {
    // Error occurred
    console.error('Error: ' + xhr.status);
  }
};
// Send request
xhr.send();

Example using fetch API:

// Using fetch
fetch('/api/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
  })
  .then(data => {
    // Update DOM or process data
    console.log(data);
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });
What is AJAX and how is this technology fundamentally… - sobes.tech