###### Table of Contents
- [[]]
- [[]]
- [[]]
- [[]]
#### How AJAX works
1. Create an XHR object - this step tells the browser to get ready; you want to send an AJAX request and the browser needs to create an object that has all the methods needed to send and receive data:
```js
const xhr = new XMLHttpRequest();
```
2. Define a callback function - this is the programming you want to run when the server returns its response. The callback is where you process the returned data and update the HTML on the page:
```js
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// do some code magic
document.getElementById('container').innerHTML = xhr.responseText;
}
};
```
3. Open a request - In this step, you give the browser two pieces of information:
- the method that will be used to send the request (e.g., GET or POST)
- the URL where the request is sent:
```js
xhr.open('GET', 'sidebar.html');
```
4. Send the request - Finally send off the request
```js
xhr.send();
```
Steps 1 - 4 all together:
```JavaScript
const xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.open("GET", "https://missinfo.tv/wp-json/v2/posts", true);
xhr.send();
```
#### XMLHttpRequest - readyState
Each XHR client that is created has a `readyState` property, which specifies the current status of XHR client.
_There are five discrete states_:
- 0 : uninitialized xhr created
- 1 : loading .open() has been called
- 2 : loaded .send() has been called
- 3 : interactive data received, but not finished
- 4 : complete request finished
#### Handle the Response with a Callback
To complete the call to the server, assign a callback function to the `onreadystatechange` event. The `onreadystatechange` event is called five times, as the state changes from 0 - 5 (see states above);
The `onreadystatechange` event handler should do the following:
1. Check the readyState for the value 4 (complete).
2. Check the response status for the value 200 (status okay).
3. Then work with the returned data supplied in `responseText`.
### Examples:
```js
// AJAX GET request
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('demo').innerHTML = xhr.responseText;
}
}
xhr.open('GET', 'https://example.com/?sortBy=name', true);
xhr.send();
```
```js
// AJAX POST request
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
}
xhr.open('POST', 'https://example.com/', true);
xhr.setRequestHeader('Content-type,' 'application/json');
xhr.send(JSON.stringify({ fname: "Keisha", lname: 'Smith'}));
```
#### More info
[[HTTP]]
___
**Tags**: #ajax #xhr