Asynchronous calls with XMLHttpRequest
AJAX enables HTTP requests to be made not only during the load time of a web page but also anytime after a page initially loads. This allows adding dynamic behavior to a webpage. This is essential for giving a good user experience without reloading the webpage for transferring data to and from the web server.
The XMLHttpRequest (XHR) web API provides the ability to make the actual asynchronous request and uses AJAX to handle the data from the request.
The given code block is a basic example of how an HTTP GET request is made to the specified URL.
The query string in a URL
Query strings are used to send additional information to the server during an HTTP GET request.
The query string is separated from the original URL using the question mark character
In a query string, there can be one or more key-value pairs joined by the equal character
For separating multiple key-value pairs, an ampersand character
& is used.
Query strings should be url-encoded in case of the presence of URL unsafe characters.
XMLHttpRequest GET Request Requirements
The URL may contain additional data in the query string. For an HTTP GET request, the request type must be
HTTP POST request with the
XMLHttpRequest API, a request type, response type, request URL, request body, and handler for the response data must be provided. The request body is essential because the information sent via the POST method is not visible in the URL. The request type must be
POST for this case. The response type can be a variety of types including array buffer, json, etc.
promise url parameter fetch api
fetch() request will accept a URL parameter, send a request and contain a success and failure promise handler function.
In the example, the block of code begins by calling the
fetch() function. Then a
then() method is chained to the end of the
fetch(). It ends with the response callback to handle success and the rejection callback to handle failure.
ok property fetch api
In a Fetch API function
ok property of a response checks to see if it evaluates to
false. In the code example the
.ok property will be
true when the HTTP request is successful. The
.ok property will be
false when the HTTP request is unsuccessful.
Fetch API Function
The Fetch API function
fetch() can be used to create requests. Though accepting additional arguments, the request can be customized. This can be used to change the request type, headers, specify a request body, and much more as shown in the example block of code.
JSON Formatted response body
.json() method will resolve a returned promise to a JSON object, parsing the body text as JSON.
The example block of code shows