Update the DOM using AJAX

Rumman Ansari   Software Engineer   2023-03-26   165 Share
☰ Table of Contents

Table of Content:


Update the DOM using AJAX

By using the response from the server, you can update the DOM. One way of doing that is by using getElementById. Consider the same example from the previous card


<body>
<p id="myElement"></p>
<script>
var request= new XMLHttpRequest();

request.open('GET','example.txt',true);

request.send();

request.onreadystatechange = function() {
  if(request.readyState == 4 && request.status == 200){
    console.log(request);
    document.getElementById("myElement").innerHTML =request.responseText;
 }
};
</script>
</body>

Explanation:

Here the javascript will find the element with the required id and replace it with the response from the server. This can also be done using getElementByTagName which you should be familiar with previous topics.

  1. var request= new XMLHttpRequest();
  • This line creates a new instance of the XMLHttpRequest object, which is used to make HTTP requests.
  1. request.open('GET','example.txt',true);
  • This line initializes a request. The first argument is the HTTP method, in this case 'GET', which is used to retrieve data from a server. The second argument is the url of the file to be retrieved, in this case 'example.txt' and the third argument is a boolean value that determines whether the request is asynchronous or not. In this case, it is true which means it will be an asynchronous request.
  1. request.send();
  • This line sends the request to the server.
  1. request.onreadystatechange = function() {
  • This line assigns a function to the onreadystatechange property of the request object. This function will be called whenever the readyState of the request changes.
  1. if(request.readyState == 4 && request.status == 200){
  • This line checks if the readyState of the request is 4 (request finished and response is ready) and the status is 200 (OK).
  1. console.log(request);
  • This line logs the entire request object to the console.
  1. document.getElementById("myElement").innerHTML =request.responseText;
  • This line sets the innerHTML of the element with the id "myElement" to the responseText of the request. The responseText is the text received from the server.