AJAX Introduction

AJAX is a developer’s dream, because you can:

  • Read data from a web server - after the page has loaded
  • Update a web page without reloading the page
  • Send data to a web server - in the background

AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request data from a web server)
  • JavaScript and HTML DOM (to display or use the data)

AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

XMLHttpRequest

1
2
3
4
5
6
7
8
9
10
11
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();

// Define a callback function
xhttp.onload = function() {
// Here you can use the Data
}

// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

1
2
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method Description
open(method, url, async) Specifies the type of request method: the type of request: GET or POST url: the server (file) location async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)

The url - A File On a Server

The url parameter of the open() method, is an address to a file on a server:

1
xhttp.open("GET", "ajax_test.asp", true);

Server Response

Server Response Properties

Property Description
responseText get the response data as a string
responseXML get the response data as XML data
1
document.getElementById("demo").innerHTML = xhttp.responseText;