Get request using AJAX by making Custom HTTP library
The task is to show how the XMLHttpRequest can be used to get data from an API by making custom HTTP library. I will be taking a fake API that will contain an array of objects as an example and from that API, we will show to get data by XMLHttpRequest method by making a custom HTTP library.
What is Ajax?
Note: First, make an HTML file and add the HTML markup according to the need. In the bottom of the body, two script files namely “library.js” and “app.js” in the same order are attached.
Approach: Steps required to make “library.js” file are as follows.
- In library.js file, make a function easyHTTP to initialize a new XMLHttpRequest() method.
- Set easyHTTP.prototype.get to a function which contains two parameters ‘url’ and a callback.
- Now initiate an object using open function. It takes three parameters, the first one is type (GET or POST or PUT or DELETE), second is the URL for the API and last one is a boolean value (“true” means asynchronous call and “false” means synchronous call).
- Now we will use onload function to display the data. The onload function is executed after the API call is done. We will check for the success status. If the status code is 200, then we will run a callback function which itself contains two arguments error and response text. If status code is not 200, the callback function will simply print the error message.
- Last step is to send the request using the send() function.
Steps required to create app.js file
- First of all instantiate easyHTTP with new keyword.
- Pass URL and a callback function in get prototype function.
- The callback function contains two arguments error to print errors occurring and response, to get the actual response.
Implementation of above steps: