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.
xhttp.onload = function() { document.getElementById(“demo”).innerHTML = this.responseText; } xhttp.open(“GET”, “ajax_info.txt”); xhttp.send(); |
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.
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 } |