How to use an HTTP GET or POST for Ajax Calls?


We need to use JavaScript, and an AJAX library like jQuery, Axios, or Fetch API to make an AJAX call using HTTP GET or POST. Ajax (Asynchronous JavaScript and XML) creates fast and dynamic web pages by updating content asynchronously without reloading the entire page. It uses JavaScript to send and receive data from a server, which can be in the form of XML, JSON, or plain text. This tutorial will teach us to use an HTTP GET or POST for Ajax Calls.

Ajax has two common types of requests: GET and POST.

GET Request

The GET request is used to retrieve data from a server. GET requests are commonly used to retrieve data from an API, as they do not make any changes to the server and are therefore considered safe and idempotent.

Syntax

Users can follow the below syntax to use GET request for Ajax Calls using javascript’s ‘XMLHttpRequest’ object.

let xhr = new XMLHttpRequest();
xhr.open("GET", "URL", true);
xhr.send(); 

This will create a new ‘XMLHttpRequest’ object and opens a GET request to the given URL. Finally, the xhr.send( ) method is used to send the GET request to the server.

Note that you will have to provide the API URL from which you want to retrieve the data.

Example

The below example demonstrates how to make a GET request in JavaScript to retrieve data from the https://jsonplaceholder.typicode.com/posts API. The code uses the XMLHttpRequest object to open a GET request and handle the response from the server. The response data is parsed into a JSON object, and the first 3 posts' titles are displayed on the page using the innerHTML property.

JSONPlaceholder API is a free and open-source API for testing and prototyping. You can use any other API also.

<html>
<body>
   <h2><i>GET</i> Method Example</h2>
   <h3>Top 3 Blog Posts:</h3>
   <div id = "posts"> </div>
   <script>
      let xhr = new XMLHttpRequest();
      xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
      xhr.onreadystatechange = function() {
         if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
            let data = JSON.parse(xhr.responseText);
            let output = "";
            for (let i = 0; i < 3; i++) {
               output += "<p>" + data[i].title + "</p>";
            }
            document.getElementById("posts").innerHTML = output;
         }
      };
      xhr.send();
   </script>
</body>
</html>

POST Request Using XMLHttpRequest Object

XMLHttpRequest can be used to make POST requests, which is similar to GET requests but with the data sent in the request body rather than the URL. The open method is used to set the request method as "POST" and URL, the send method is used to send the data, and the onreadystatechange event is used to handle the response from the server. The content type and other headers can also be set as needed.

Syntax

Users can follow the below syntax to use POST request for Ajax Calls.

var xhr = new XMLHttpRequest(); 
xhr.open("POST", "URL", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(postData)); 

Example

The below example demonstrates a POST request using the XMLHttpRequest object. We have created a form with two input fields for entering a post title and body and a submit button. When the submit button is clicked, the sendPostRequest() function is called, which creates a POST request to the "https://jsonplaceholder.typicode.com/posts" endpoint. The function sets the request header to indicate the content type is JSON and sends the post data in JSON format. We also display success status.

<html>
<body>
   <h2><i>POST</i> request example</h2>
   <input type = "text" id = "title" placeholder = "Enter post title">
   <br> <br>
   <textarea id = "body" placeholder = "Enter post body"></textarea><br>
   <br>
   <button onclick = "sendPostRequest()">Submit</button> <br> <br>
   <div id = "response" ></div>
   <script>
      function sendPostRequest() {
         var postData = {
            title: document.getElementById("title").value,
            body: document.getElementById("body").value
         };
         var xhr = new XMLHttpRequest();
         xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
         xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
         xhr.send(JSON.stringify(postData));
         xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 201) {
               document.getElementById("response").innerHTML = "Post request successful: " + xhr.responseText;
            } else {
               document.getElementById("response").innerHTML = "Post request failed: " + xhr.responseText;
            }
         };
      }
   </script>
</body>
</html> 

POST Request Using Fetch

fetch is a modern method for making network requests. It makes a POST request by passing the URL, and an options object as arguments. The options object specifies the request method as "POST" and sets the header "Content-Type" to "application/json". The request data is passed as a stringified JSON object in the body property of the options object. The response from the server is then processed using .then() method, which returns the JSON data from the response.

Example

The below example demonstrates a POST request using fetch. A simple form sends a POST request to a JSON placeholder API. On submit, the response data is displayed with formatting in an HTML pre tag.

<html>
<body>
   <h2>Create New Blog Post:</h2>
   <form>
      <input type = "text" id = "title" placeholder = "Title" required>
      <textarea id = "body" placeholder = "Body" required> </textarea>
      <button type = "button" id = "submitBtn"> Submit </button>
   </form> <br>
   <h2>Response:</h2>
   <pre id = "response" ></pre>
   <script>
      document.getElementById("submitBtn").addEventListener("click", function() {
         let title = document.getElementById("title").value;
         let body = document.getElementById("body").value;
         let data = {
            title: title,
            body: body 
         };
         fetch("https://jsonplaceholder.typicode.com/posts", {
            method: "POST",
            headers: {
               "Content-Type": "application/json"
            },
            body: JSON.stringify(data)
         })
         .then(response => response.json())
         .then(data => {
            document.getElementById("response").innerHTML = JSON.stringify(
               data,
               null,
               2
            );
         });
      });
   </script>
</body>
</html>

We have learned to use an HTTP GET or POST for Ajax Calls using JavaScript’s XMLHttpRequest object and using fetch with different examples.

Updated on: 22-Feb-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements