> For the complete documentation index, see [llms.txt](https://gzqsjtu.gitbook.io/workspace/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gzqsjtu.gitbook.io/workspace/javascript/ajax.md).

# AJAX

### XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-in `XMLHttpRequest` object.

Syntax for creating an `XMLHttpRequest`&#x20;

var xhttp = new XMLHttpRequest();

request

```
$.ajax({
  url: "http://localhost:8080/login",
  type: 'GET',
  // Fetch the stored token from localStorage and set in the header
  headers: {"Authorization": localStorage.getItem('token')}
});

$.ajax({
  url: "http://localhost:8080/login",
  type: "POST",
  headers: { Authorization: $`Bearer ${localStorage.getItem("token")}` },
  data: formData,
  error: function(err) {
    switch (err.status) {
      case "400":
        // bad request
        break;
      case "401":
        // unauthorized
        break;
      case "403":
        // forbidden
        break;
      default:
        //Something bad happened
        break;
    }
  },
  success: function(data) {
    console.log("Success!");
  }
});
```

### XMLHttpRequest Object Methods

| Method                                | Description                                                                                                                                                                                                                                                |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| new XMLHttpRequest()                  | Creates a new XMLHttpRequest object                                                                                                                                                                                                                        |
| abort()                               | Cancels the current request                                                                                                                                                                                                                                |
| getAllResponseHeaders()               | Returns header information                                                                                                                                                                                                                                 |
| getResponseHeader()                   | Returns specific header information                                                                                                                                                                                                                        |
| open(*method, url, async, user, psw*) | <p>Specifies the request<br><br><em>method</em>: the request type GET or POST<br><em>url</em>: the file location<br><em>async</em>: true (asynchronous) or false (synchronous)<br><em>user</em>: optional user name<br><em>psw</em>: optional password</p> |
| send()                                | <p>Sends the request to the server<br>Used for GET requests</p>                                                                                                                                                                                            |
| send(*string*)                        | <p>Sends the request to the server.<br>Used for POST requests</p>                                                                                                                                                                                          |
| setRequestHeader()                    | Adds a label/value pair to the header to be sent                                                                                                                                                                                                           |

### XMLHttpRequest Object Properties

| Property           | Description                                                                                                                                                                                                                   |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| onreadystatechange | Defines a function to be called when the readyState property changes                                                                                                                                                          |
| readyState         | <p>Holds the status of the XMLHttpRequest.<br>0: request not initialized<br>1: server connection established<br>2: request received<br>3: processing request<br>4: request finished and response is ready</p>                 |
| responseText       | Returns the response data as a string                                                                                                                                                                                         |
| responseXML        | Returns the response data as XML data                                                                                                                                                                                         |
| status             | <p>Returns the status-number of a request<br>200: "OK"<br>403: "Forbidden"<br>404: "Not Found"<br>For a complete list go to the <a href="https://www.w3schools.com/tags/ref_httpmessages.asp">Http Messages Reference</a></p> |
| statusText         | Returns the status-text (e.g. "OK" or "Not Found")                                                                                                                                                                            |

## Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the `XMLHttpRequest` object:xhttp.open("GET", "ajax\_info.txt", true);\
xhttp.send();

| Method                   | Description                                                                                                                                                                  |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| open(method, url, async) | <p>Specifies the type of request<br><br>method: the type of request: GET or POST<br>url: the server (file) location<br>async: true (asynchronous) or false (synchronous)</p> |
| send()                   | Sends the request to the server (used for GET)                                                                                                                               |
| send(string)             | Sends the request to the server (used for POST)                                                                                                                              |

A simple `GET` request:

xhttp.open("GET", "demo\_get.asp", true);\
xhttp.send();

xhttp.open("GET", "demo\_get2.asp?fname=Henry\&lname=Ford", true); xhttp.send();

```
fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });
```
