DEV Community

Cover image for XmlHttpRequest (XHR) Object Request
Mihindu Ranasinghe
Mihindu Ranasinghe

Posted on • Updated on

XmlHttpRequest (XHR) Object Request

NOTE


Lets code how to Get some data from a text file & display them in a web page using XHR Object

  • Text file name "data.txt"
  • Html page "index.html" (Only contains a button with the #id of 'button').

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" integrity="sha256-ECB9bbROLGm8wOoEbHcHRxlHgzGqYpDtNTgDTyDz0wg=" crossorigin="anonymous" />

    <title>Document</title>
</head>
<body>
   <div class="container">
       <button id="button">Get Data</button>
            <div class="" id="output"></div>
    </div> 
<script src="app.js"></script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

👏👏Let's code the JavaScript part - app.js...

document.getElementById('button').addEventListener('click',loadData);
function loadData(){

    //Create an XHR object
    const xhr = new XMLHttpRequest();

    //OPEN
    xhr.open('GET','data.txt',true); //Get Method used
    console.log('READYSTATE', xhr.readyState);//Just to check the ready state

    xhr.onload = function(){ //readystate is 4 
        console.log('READYSTATE', xhr.readyState);//just to check the ready state
        if(this.status === 200){//Check whether the http state is 200 or not

            document.getElementById('output').innerHTML=`<h1>${this.responseText}</h1>`;
        }
    }

   xhr.send();
}


Enter fullscreen mode Exit fullscreen mode

Output When press 'Get Data'

OutPut

So what is "READYSTATE" and "HTTP status" ??

READYSTATE means the status of your request readyness. There are some values of ReadyState with representing several meanings.

👏ReadyState Values:

    0: request not initialized
    1: server connection established
    2: request received
    3: processing request
    4: request finished and response is ready
Enter fullscreen mode Exit fullscreen mode

👏HTTP Status:

    200:"OK"
    403:"Forbidden"
    404:"Not Found"
Enter fullscreen mode Exit fullscreen mode

Also you can GET data using this below method instead of "xhr.onload",
You can try this method and get the same result.

NOTE

  • This method is now not in use... This is a very old method. I never recommend it.

//This one is old method

    xhr.onreadystatechange = function(){
        console.log('READYSTATE', xhr.readyState);
        if(this.status === 200 && this.readyState === 4){
            console.log(this.responseText);
        }
    }


Enter fullscreen mode Exit fullscreen mode

👏👏onerror

You can display an error message if something bad happened to your request

xhr.onerror=function(){
        console.log('request error...');
    }

    xhr.send();

Enter fullscreen mode Exit fullscreen mode

👏👏Bonus Tip

when the readystate is 3, that means it is in processing state. So you can implement a Spinner or a Loader while processing a request.

This code line will easily do it for you


xhr.onprogress = function(){ //readystate is 3, u can use it for loader, spinners
        //console.log('READYSTATE', xhr.readyState);
        //Spinner or Loader
    }

Enter fullscreen mode Exit fullscreen mode

👉What's Next?
IF YOU HAVE DONE READING "XmlHttpRequest (XHR) Object Request" ARTICLE, I SUGGEST YOU TO READ MY NEXT ARTICLE.

Thank You

Hope you all enjoyed and learned something on this. Please let me know your comments suggestions and any questions you have about this blog.

👉 Visit me - https://mihinduranasinghe.com/

Top comments (3)

Collapse
 
felixdorn profile image
Info Comment hidden by post author - thread only accessible via permalink
FĂ©lix Dorn • Edited

First, what about fetch, you don't even talk about it and fetch is the implicitly recommend way to do it!?
Second, you never explain what you do, or put a link to a documentation? Is it this an article for beginners or just words that make them think how much this is complicated while it's not?

Collapse
 
mihinduranasinghe profile image
Mihindu Ranasinghe • Edited

Dear Felix , thank you for commenting your feedback. I have done some changes to my article to make this more simple and in the first three images will explain it simply. There are some additional functions to diplay an error or set a loader or a spinner..
There is an introduction article I've written before this article
dev.to/mihinduranasinghe/introduct...

Collapse
 
felixdorn profile image
Info Comment hidden by post author - thread only accessible via permalink
FĂ©lix Dorn

It looks better, but anyways, before teaching anything,you should know it 100%.

Some comments have been hidden by the post's author - find out more