D DevBrainBox

JavaScript API Ajax

JS

What is AJAX?

AJAX stands for: Asynchronous JavaScript and XML

It is not a programming language, but a technique that uses JavaScript to send and receive data from a server asynchronously, without reloading the entire web page.

  • This makes web pages faster and more dynamic.
  • Today, it often deals with JSON (not XML) because JSON is lighter and easier to work with in JavaScript.

How does AJAX work?

  • JavaScript code on your page sends a request to a server (e.g., asking for some data).
  • The server processes the request and sends back a response (usually in JSON or XML format).
  • JavaScript receives this response and updates part of the web page, without refreshing the whole page.

Example using the fetch API (modern way)

// Example: fetch data from an API and update the page
fetch('https://api.example.com/users')
.then(response => response.json()) // parse JSON
.then(data => {
 console.log(data);
 document.getElementById('output').textContent = JSON.stringify(data);
 })
.catch(error => console.error('Error:', error));
  • fetch is a modern built-in JavaScript API for AJAX requests.
  • It returns a Promise, so you can use .then() and .catch().

AJAX lets JavaScript make HTTP requests to the server and update the web page without reloading, making the user experience smooth and dynamic.

On this page