Web Technologies

How to make a basic Ajax call using XMLHttpRequest object – Tutorial 2

First create a message.txt file with single line text: “Hi I am from Ajax file located on server”

Now in your html file ceate a H1 tag & a simple button using this code

<h1 id="wrapper">Hello Brother. How r you? all good?</h1>
<button onclick="loadmessage()">Click to change content by Ajax</button>

Now you have to create a JS function in your JS file which you need to link with your HTML file.

function loadmessage() {
  // alert("i am clicked");

  // Create an object First
  let xhr = new XMLHttpRequest();

  // Open a connection with server
  xhr.open("GET", "./message.txt", true);
  console.log(xhr.status, xhr.readyState);

  // Now we need to declare a function telling that
  // What we should do if we received a response
  // Then only we need to call send method
  xhr.onload = function () {
    //console.log(this);
    console.log(xhr.status, xhr.readyState);
    document.getElementById("wrapper").innerText = this.responseText;
  };

  // Finally send request
  xhr.send();
}

Boom!!! You are done with simple Ajax call.

Next lession