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.

API link: https://jsonplaceholder.typicode.com/posts

What is Ajax?

Ajax or Asynchronous JavaScript and XML is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance. To read more about Ajax, click on https://www.geeksforgeeks.org/ajax-introduction/.

Prerequisites: Only the basic knowledge of HTML, CSS, and JavaScript are required.



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.

  1. In library.js file, make a function easyHTTP to initialize a new XMLHttpRequest() method.
  2. Set easyHTTP.prototype.get to a function which contains two parameters ‘url’ and a callback.
  3. 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).
  4. 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.
  5. Last step is to send the request using the send() function.

Steps required to create app.js file

  1. First of all instantiate easyHTTP with new keyword.
  2. Pass URL and a callback function in get prototype function.
  3. The callback function contains two arguments error to print errors occurring and response, to get the actual response.
    1. Implementation of above steps:
      HTML file:

      HTML

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      <!DOCTYPE html>
      <html lang="en">
        
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content=
              "width=device-width, initial-scale=1.0">
        
          <title>Get request</title>
      </head>
        
      <body>
          <h1>
              Get request using xmlhttpRequest/ 
              Ajax by making custom HTTP library.
          </h1>
        
          <!-- Including library.js and app.js files -->
          <script src="library.js"></script>
          <script src="app.js"></script>
      </body>
        
      </html>

      chevron_right

      
      

      library.js:

      Javascript

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      function easyHTTP() {
        
          // Initialising new XMLHttpRequest method
          this.http = new XMLHttpRequest();
      }
        
      // Make an HTTP GET Request
      easyHTTP.prototype.get = function (url, callback) {
        
          // Open an obejct (GET/POST, PATH, 
          // ASYN-TRUE/FALSE) 
          this.http.open('GET', url, true);
        
          // Assigning this to self to have  
          // scope of this into the function
          let self = this;
        
          // When response is ready 
          this.http.onload = function () {
        
              // Checking status
              if (self.http.status === 200) {
        
                  // Callback function (Error, response text)
                  callback(null, self.http.responseText);
              } else {
        
                  // Callback function (Error message)
                  callback('Error: ' + self.http.status);
              }
          }
        
          // At last send the request 
          this.http.send();
      }

      chevron_right

      
      

      app.js

      Javascript

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // Instantiating easyHTTP
      const http = new easyHTTP;
        
      // Get prototype method(URL, callback(error,
      // response text))
          function (err, posts) {
              if (err) {
                  console.log(err);
              } else {
        
                  // parsing string data to object
                  let data = JSON.parse(posts);
                  console.log(data);
              }
          });

      chevron_right

      
      

      Output:

      full-stack-img




      My Personal Notes arrow_drop_up

      Check out this Author's contributed articles.

      If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

      Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.