XmlHttpRequest (XHR) Object Request
Tags: javascript, xmlhttprequest
Published: 2020-01-17 04:04:40

###**NOTE**
- IF YOU ARE NEW TO THIS ARTICLE, I RECOMMEND TO READ "Introduction To Asynchronous JavaScript" ARTICLE BEFORE STARTING THIS.

- [Introduction To Asynchronous JavaScript](https://dev.to/mihinduranasinghe/introduction-to-asynchronous-javascript-351a)

---------------------------------------------------------------------------------

###**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').

```html

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

```javascript
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](https://thepracticaldev.s3.amazonaws.com/i/ggfp4t4fgdu9k6vrllsm.PNG)

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

```javascript

//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*
```javascript 
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***

```javascript

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.

- [How to make/code XHR Object Request using AJaX ?](https://dev.to/mihinduranasinghe/working-with-ajax-json-lfn)

##**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/](https://mihinduranasinghe.com/)