Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

AJAX Intro

AJAX is a developer’s dream because it enables:

  • Reading data from a web server after the page has loaded
  • Updating a web page dynamically without a full reload
  • Sending data to a web server in the background

AJAX Example Explained

HTML Page

<!DOCTYPE html>
<html>
<body>

<div id=”demo”>
  
<h2>Let AJAX change this text</h2>
  
<button type=”button” onclick=”loadDoc()”>Change Content</button>
</div>

</body>
</html>

The HTML page includes a <div> section for displaying information from a server and a <button> that triggers a function when clicked.

This function fetches data from a web server and updates the <div> with the retrieved information.

Function loadDoc()

function loadDoc() {
  
const xhttp = new XMLHttpRequest();
  xhttp.onload = 
function() {
    document.getElementById(
“demo”).innerHTML = this.responseText;
    }
  xhttp.open(
“GET”“ajax_info.txt”true);
  xhttp.send();
}

What is AJAX?

AJAX (Asynchronous JavaScript and XML) is not a programming language but a technique that combines:

  • The browser’s built-in XMLHttpRequest object to fetch data from a web server
  • JavaScript and the HTML DOM to process and display the data

The name “AJAX” can be misleading; while it suggests using XML for data transport, AJAX applications often use plain text or JSON for data exchange just as commonly.

AJAX enables web pages to update asynchronously by exchanging data with a web server in the background, allowing specific parts of a page to be refreshed without reloading the entire page.

 

How AJAX Works

pic_ajax 2

1. An event happens on a web page, such as the page loading or a button being clicked.
2. JavaScript creates an XMLHttpRequest object.
3. The XMLHttpRequest object sends a request to the web server.
4. The server handles the request.
5. The server returns a response to the web page.
6. JavaScript reads the response.
7. JavaScript performs the appropriate action, such as updating the page.

Modern Browsers (Fetch API)

Modern browsers support the Fetch API as an alternative to the XMLHttpRequest object.

The Fetch API provides a simpler interface for making HTTP requests to web servers, performing the same tasks as XMLHttpRequest with greater ease.