POST request using AJAX by making Custom HTTP library

The task is to show how the XMLHttpRequest can be used to POST data to an API by making custom HTTP library. We will be taking a fake API which will contain Array of objects as an example and from that API we will show to POST data by XMLHttpRequest method by making a custom HTTP library.

Used API: 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 is required to go.

Note: First make a HTML file and add the HTML markup according to the requirement. In the bottom of the body tag attach two scripts file as library.js and app.js in the same order.



Steps required to make library.js File:

  1. In library.js file, make a function easyHTTP to initialize a new XMLHttpRequest() method.
  2. Set easyHTTP.prototype.post to a function which contains three parameters ‘url’, data and callback.
  3. Now open an object using this.http.open function. It takes three parameters, the first one is request 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. But before that first we need to set content-type with this.http.setRequestHeader method and also assign this keyword to self to have scope of this keyword into onload function. The onload function is executed after the API call is done. This function will run a callback function which has two arguments as error and response text.
  5. Last step is to send the request using the send() function. It should be noted that send() function needs to send data after converting object data to string using JSON.stringify(data).

Steps required to make app.js File:

  1. First of all instantiate easyHTTP with new keyword.
  2. Create a custom data(object) to post.
  3. Pass URL, data and a callback function in post prototype function.
  4. The callback function contains two arguments error to print if any error occurs and response to get the actual response.

Filename: index.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>POST request</title>
</head>
<body>
    <h1>
        POST 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


Filename: app.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Instantiating easyHTTP
const http = new easyHTTP;
  
// Create Data
const data = {
  title: 'Custom HTTP Post',
  body: 'This is a custom post data'
};
  
  
// Post prototype method(url, data,
// response text)
http.post(
   data, 
   function(err, post) {
      if(err) {
        console.log(err);
      } else {
        // Parsing string data to object
        // let data = JSON.parse(posts); 
        console.log(post);
    }
});

chevron_right


Filename: library.js

filter_none

edit
close

play_arrow

link
brightness_4
code

  function easyHTTP() {
  
    // Initializing new XMLHttpRequest method. 
    this.http = new XMLHttpRequest();
  }
  
  // Make an HTTP POST Request
  easyHTTP.prototype.post = function(url, data, callback) {
  
  // Open an object (POST, PATH, ASYN-TRUE/FALSE) 
  this.http.open('POST', url, true);
  
  // Set content-type
  this.http.setRequestHeader('Content-type', 'application/json');
  
  // Assigning this to self to have  
  // scope of this into the function
  let self = this;
  
  // When response is ready 
  this.http.onload = function() {
  
    // Callback function (Error, response text)
    callback(null, self.http.responseText);
  }
  
  // Since the data is an object so
  // we need to stringify it
  this.http.send(JSON.stringify(data));
}

chevron_right


Output:
Open your index.html file in any browser and open its console by right click->Inspect element->console. Hence you will see the below result.

Note: It contains one additional key-value pair as ‘id’ 101. Don’t worry about this as this is created by default.

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.