loading...
Cover image for XmlHttpRequest (XHR) Object Request

XmlHttpRequest (XHR) Object Request

mihinduranasinghe profile image Mihindu Ranasinghe | CyberCats ・2 min read

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>

πŸ‘πŸ‘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();
}


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

πŸ‘HTTP Status:

    200:"OK"
    403:"Forbidden"
    404:"Not Found"

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);
        }
    }


πŸ‘πŸ‘onerror

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

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

    xhr.send();

πŸ‘πŸ‘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
    }

πŸ‘‰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.

Posted on by:

mihinduranasinghe profile

Mihindu Ranasinghe | CyberCats

@mihinduranasinghe

Sri Lanka Section Lead at IEEE Xtreme | Web Developer at SL Inspire | Looking for a Software Engineering Internship

Discussion

markdown guide
 

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?

 

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...