How AJAX Accesses Web Servers from a Web Page
AJAX (Asynchronous JavaScript and XML) allows a web page to communicate with a server without reloading the entire page.
The Common Confusion
A common question is:
If JavaScript runs once and stops, how can AJAX keep talking to a web server?
This confusion comes from misunderstanding how JavaScript execution works in the browser.
The Key Idea
JavaScript does not run only once. It runs again whenever an event happens.
AJAX works using:
- Asynchronous operations
- Browser-managed networking
- Callbacks or promises
What AJAX Really Is
AJAX stands for Asynchronous JavaScript And XML. In practice, it means:
- JavaScript sends a request to a server
- The browser waits for the response
- JavaScript runs again when the response arrives
The page does not reload during this process.
Who Is Doing the Waiting?
JavaScript does not wait for the server.
Instead:
- The browser sends the request
- JavaScript finishes execution
- The browser waits for the network response
- The browser triggers a callback when data arrives
Timeline of an AJAX Request
- Page loads and JavaScript sends a request
- JavaScript becomes idle
- Server responds
- Browser queues an event
- JavaScript runs again to handle the response
The Event Loop
The browser uses an event loop to manage:
- Network responses
- User interactions
- Timers
When an event occurs, JavaScript is called to handle it.
Simple AJAX Example
fetch("/api/data")
.then(response => response.json())
.then(data => {
console.log("Data received:", data);
});
The request is sent immediately. The response handler runs later, when the data is available.
Why the Page Does Not Reload
Traditional web requests reload the entire page. AJAX updates only parts of the page using JavaScript and the DOM.
Summary
AJAX works because the browser waits for the server and calls JavaScript back when the response arrives.