Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The onload Property

With the XMLHttpRequest object, you can specify a callback function to be executed when the request receives a response.

This function is defined in the onload property of the XMLHttpRequest object.

Example

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

Multiple Callback Functions

When dealing with multiple AJAX tasks on a website, it’s recommended to create a single function for executing the XMLHttpRequest object and separate callback functions for each AJAX task.

The function call should include the URL and specify the callback function to be triggered once the response is ready.

Example

loadDoc(url-1, myFunction1);

loadDoc(url-2, myFunction2);

function loadDoc(url, cFunction) {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {cFunction(this);}
  xhttp.open(“GET”, url);
  xhttp.send();
}

function myFunction1(xhttp) {
  // action goes here
}
function myFunction2(xhttp) {
  // action goes here
}