JavaScript TutorialDatatypes in JavaScriptEvaluating JavaScriptFunctional JavaScriptJavaScript .postMessage() and MessageEventJavaScript AJAXJavaScript Anti-patternsJavaScript Arithmetic (Math)JavaScript ArraysJavaScript Arrow FunctionsJavaScript Async functions (async/await)JavaScript Async IteratorsJavaScript Automatic Semicolon Insertion - ASIJavaScript Battery Status APIJavaScript Behavioral Design PatternsJavaScript Binary DataJavaScript Bitwise operatorsJavaScript Bitwise Operators - Real World Examples (snippets)JavaScript BOM (Browser Object Model)JavaScript Built-in ConstantsJavaScript CallbacksJavaScript ClassesJavaScript CommentsJavaScript Comparison OperationsJavaScript ConditionsJavaScript ConsoleJavaScript Constructor functionsJavaScript Context (this)JavaScript CookiesJavaScript Creational Design PatternsJavaScript Custom ElementsJavaScript Data attributesJavaScript Data ManipulationJavaScript DateJavaScript Date ComparisonJavaScript DebuggingJavaScript Declarations and AssignmentsJavaScript Destructuring assignmentJavaScript Detecting browserJavaScript EnumerationsJavaScript Error HandlingJavaScript Escape SequencesJavaScript EventsJavaScript execCommand and contenteditableJavaScript FetchJavaScript File API, Blobs and FileReadersJavaScript Fluent APIJavaScript FunctionsJavaScript GeneratorsJavaScript GeolocationJavaScript Global error handling in browsersJavaScript HistoryJavaScript How to make iterator usable inside async callback functionJavaScript IndexedDBJavaScript InheritanceJavaScript Intervals and TimeoutsJavaScript JSONJavaScript Linters - Ensuring code qualityJavaScript LocalizationJavaScript LoopsJavaScript MapJavaScript Memory efficiencyJavaScript Method ChainingJavaScript Modals - PromptsJavaScript Modularization TechniquesJavaScript ModulesJavaScript NamespacingJavaScript Navigator ObjectJavaScript Notifications APIJavaScript ObjectsJavaScript Performance TipsJavaScript PromisesJavaScript Prototypes, objectsJavaScript ProxyJavaScript Regular expressionsJavaScript requestAnimationFrameJavaScript Reserved KeywordsJavaScript Same Origin Policy & Cross-Origin CommunicationJavaScript ScopeJavaScript ScreenJavaScript Security issuesJavaScript Selection APIJavaScript Server-sent eventsJavaScript SetJavaScript Setters and GettersJavaScript Strict modeJavaScript StringsJavaScript SymbolsJavaScript Tail Call OptimizationJavaScript Template Literals

JavaScript AJAX

From WikiOD

AJAX stands for "Asynchronous JavaScript and XML". Although the name includes XML, JSON is more often used due to it's simpler formatting and lower redundancy. AJAX allows the user to communicate with external resources without reloading the webpage.

Remarks[edit | edit source]

AJAX stands for Asynchronous JavaScript and XML. Nevertheless you can actually use other types of data and—in the case of xmlhttprequest—switch to the deprecated synchronous mode.

AJAX allows web pages to send HTTP requests to the server and receive a response, without needing to reload the entire page.

Sending and Receiving JSON Data via POST[edit | edit source]


Fetch request promises initially return Response objects. These will provide response header information, but they don't directly include the response body, which may not have even loaded yet. Methods on the Response object such as .json() can be used to wait for the response body to load, then parse it.

const requestData = {
  method : 'getUsers'

const usersPromise = fetch('/api', {
  method : 'POST',
  body : JSON.stringify(requestData)
}).then(response => {
  if (!response.ok) {
    throw new Error("Got non-2XX response from API server.");
  return response.json();
}).then(responseData => {
  return responseData.users;

usersPromise.then(users => {
  console.log("Known users: ", users);
}, error => {
  console.error("Failed to fetch users due to error: ", error);

Add an AJAX preloader[edit | edit source]

Here's a way to show a GIF preloader while an AJAX call is executing. We need to prepare our add and remove preloader functions:

function addPreloader() {
  // if the preloader doesn't already exist, add one to the page
  if(!document.querySelector('#preloader')) {
    var preloaderHTML = '<img id="preloader" src="" />';
    document.querySelector('body').innerHTML += preloaderHTML;

function removePreloader() {
  // select the preloader element
  var preloader = document.querySelector('#preloader');
  // if it exists, remove it from the page
  if(preloader) {

Now we're going to look at where to use these functions.

var request = new XMLHttpRequest();

Inside the onreadystatechange function you should have an if statement with condition: request.readyState == 4 && request.status == 200.

If true: the request is finished and response is ready that's where we'll use removePreloader().

Else if false: the request is still in progress, in this case we'll run the function addPreloader()

xmlhttp.onreadystatechange = function() {

  if(request.readyState == 4 && request.status == 200) {
    // the request has come to an end, remove the preloader
  } else {
    // the request isn't finished, add the preloader

};'GET', your_file.php, true);

Displaying the top JavaScript questions of the month from Stack Overflow's API[edit | edit source]

We can make an AJAX request to Stack Exchange's API to retrieve a list of the top JavaScript questions for the month, then present them as a list of links. If the request fails or the returns an API error, our promise error handling displays the error instead.


View live results on HyperWeb.

const url =
    '' +

fetch(url).then(response => response.json()).then(data => {
  if (data.error_message) {
    throw new Error(data.error_message);

  const list = document.createElement('ol');

  for (const {title, link} of data.items) {
    const entry = document.createElement('li');
    const hyperlink = document.createElement('a');

    hyperlink.textContent = title;
    hyperlink.href = link;
}).then(null, error => {
  const message = document.createElement('pre');
  document.body.appendChild(message); = 'red';

  message.textContent = String(error);

Using GET with parameters[edit | edit source]

This function runs an AJAX call using GET allowing us to send parameters (object) to a file (string) and launch a callback (function) when the request has been ended.

function ajax(file, params, callback) {

  var url = file + '?';

  // loop through object and assemble the url
  var notFirst = false;
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      url += (notFirst ? '&' : '') + key + "=" + params[key];
    notFirst = true;

  // create a AJAX call with url as parameter
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  };'GET', url, true);

Here's how we use it:

ajax('cars.php', {type:"Volvo", model:"300", color:"purple"}, function(response) {
  // add here the code to be executed when data comes back to this page      
  // for example console.log(response) will show the AJAX response in console

And the following shows how to retreive the url parameters in cars.php:

if(isset($_REQUEST['type'], $_REQUEST['model'], $_REQUEST['color'])) {
  // they are set, we can use them !
  $response = 'The color of your car is ' . $_REQUEST['color'] . '. ';
  $response .= 'It is a ' . $_REQUEST['type'] . ' model ' . $_REQUEST['model'] . '!';
  echo $response;

If you had console.log(response) in callback function the result in console would have been:

The color of your car is purple. It is a Volvo model 300!

Check if a file exists via a HEAD request[edit | edit source]

This function executes an AJAX request using the HEAD method allowing us to check whether a file exists in the directory given as an argument. It also enables us to launch a callback for each case (success, failure).

function fileExists(dir, successCallback, errorCallback) {
    var xhttp = new XMLHttpRequest;

    /* Check the status code of the request */
    xhttp.onreadystatechange = function() {
        return (xhttp.status !== 404) ? successCallback : errorCallback;

    /* Open and send the request */'head', dir, false);

Using GET and no parameters[edit | edit source]

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
        //parse the response in xhttp.responseText;
};"GET", "ajax_info.txt", true);


The fetch API is a newer promise-based way to make asynchronous HTTP requests.

fetch('/').then(response => response.text()).then(text => {
  console.log("The home page is " + text.length + " characters long.");

Listening to AJAX events at a global level[edit | edit source]

// Store a reference to the native method
let open =; 

// Overwrite the native method = function() {
    // Assign an event listener
    this.addEventListener("load", event => console.log(XHR), false);
    // Call the stored reference to the native method
    open.apply(this, arguments);