XHR Request

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

Table of Content:


XHR Request

  • XMLHttpRequest is an object that is used by all modern browsers to communicate with the server.
  • This object is commonly used in AJAX programming.
  • You can also update only a part of a web page using this object.
  • It helps in making synchronous and asynchronous calls to the server and retrieving data without a full page reload.
  • Let us see how to make synchronous calls and its disadvantages

Example



var request= new XMLHttpRequest();
request.open('GET','Example.txt',false);
request.send();
if(request.readyState == 4 && request.status == 200){
   console.log(request);
   document.writeln(request.responseText);
}
document.writeln("some text");


In this code, since we passed false as a parameter to open() function the browser treats this as synchronous calls and wait for the server to respond and then execute the next line.

Explanation

  1. var request= new XMLHttpRequest(); - This line creates a new instance of the XMLHttpRequest object.

  2. request.open('GET','Example.txt',false); - This line opens a new request using the GET method and specifying the file 'Example.txt' to be retrieved. The third parameter 'false' indicates that the request is synchronous and will block execution of the script until the request is completed.

  3. request.send(); - This line sends the request.

  4. if(request.readyState == 4 && request.status == 200) - This if statement checks if the request has completed (readyState == 4) and if the response status is 'OK' (status == 200). If both conditions are true, the code inside the if block will execute.

  5. console.log(request); - This line logs the entire request object to the console, allowing you to see all the properties and methods of the request object.

  6. document.writeln(request.responseText); - This line writes the response text (the contents of the file 'Example.txt') to the current web page using the writeln() method of the document object.

  7. document.writeln("some text"); - This line writes the string "some text" to the current web page using the writeln() method of the document object.