JavaScript: HTTP Request and JSON Response

Updated on Dec 27,2023

JavaScript: HTTP Request and JSON Response

Table of Contents

  1. Introduction
  2. How to Send an HTTP GET Request Using JavaScript
  3. Real-Time Example: Sending a GET Request with Current IP Address
  4. How to Send HTTP GET Request Using JavaScript
  5. Dynamically Passing Parameters in GET Request
  6. How to Send an HTTP POST Request Using JavaScript
  7. The HTTP Bin Service: Testing POST Requests
  8. Dynamic POST Requests using JavaScript
  9. Summary
  10. Conclusion

Introduction

This article will guide You through the process of sending HTTP GET and POST requests using JavaScript and how to handle the JSON response. We will start by understanding how to send a GET request with default parameters and Read the JSON response. Then, we will explore how to pass parameters from a form to send an HTTP GET request and read the response from the server. Next, we will move on to sending a POST request using JavaScript and explore a real-time example using the HTTP Bin client. Finally, we will learn how to dynamically pass form values and retrieve them in the HTML page using JavaScript.

How to Send an HTTP GET Request Using JavaScript

Before we dive into the details, let's understand the basics of sending an HTTP GET request using JavaScript. We can use the XMLHttpRequest object to make HTTP requests. By creating an instance of this object and calling the appropriate methods, we can send GET requests to a specified URL. This allows us to fetch data from a server and receive a JSON response.

Let's explore a real-time example to further understand the concept.

Real-Time Example: Sending a GET Request with Current IP Address

To illustrate how to send an HTTP GET request, we will use a Website that provides a web service. This web service returns a JSON response with information about an IP address, such as its coordinates and location. We will send a GET request with the current IP address to retrieve the JSON response.

The website we will be using is Ipin4db.com. To access the web service, you need to sign up for an API key. Once you have the API key, you can use it along with the IP address to construct the URL for the GET request.

To get started, follow these steps:

  1. Sign up for an API key on Ipin4db.com.
  2. Once you have the API key, login to your account.
  3. Navigate to the "IP Location Data" section.
  4. In the section, you will find three HTTP request methods: "IP City," "IP Country," and "IP Address."
  5. For our example, we will use the "IP City" method.
  6. Construct the URL by appending the API key, IP address, and format as parameters.
  7. The format parameter should be set to "JSON" to receive a JSON response.

Let's test the constructed URL in a browser to see the JSON response. Copy the URL and paste it into the address bar. Upon pressing Enter, you should receive the JSON response containing details about the IP address.

Now, let's move on to sending the same request using JavaScript.

How to Send HTTP GET Request Using JavaScript

To send an HTTP GET request using JavaScript, we first need to Create a simple HTML page. You can create a new HTML file with any name, such as "HTTPRequestOnload.html". Open the file in a text editor and add the basic HTML tags.

<!DOCTYPE html>
<html>
<head>
  <title>HTTP Request Onload</title>
</head>
<body>
  <h1>JavaScript GET Request Test</h1>
  <script>
    // JavaScript code to send the HTTP request and get the response
  </script>
</body>
</html>

Inside the <script> tag, we will write the JavaScript code that handles the HTTP request. We will use the XMLHttpRequest object to make the request. Here's an example of how the code should look:

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    var response = JSON.parse(this.responseText);
    alert(response);
  }
};
request.open("GET", "URL", true);
request.send();

In the above code, we create an instance of the XMLHttpRequest object and define the onreadystatechange event handler. This event is triggered whenever the readyState or status changes. Inside the event handler, we check if the request is completed (readyState === 4) and successful (status === 200). If the conditions are met, we parse the JSON response and display it using the alert function. The open method is used to specify the Type of request ("GET" in this case) and the URL to which the request is sent. Finally, we call the send method to send the request.

To test the code, simply open the HTML file in a browser. The page will send the HTTP request automatically on page load, and you should see the response displayed in an alert.

So far, we have learned how to send a GET request using JavaScript. However, what if we want to pass dynamic parameters via a form and send a request accordingly? Let's explore that next.

Dynamically Passing Parameters in GET Request

To make the GET request more dynamic, we will allow users to input an IP address and format of the response through a form. The values entered in the form will be used to construct the URL for the GET request. To achieve this, we need to modify our HTML page and add a <form> element along with the necessary input fields and a submit button.

<!DOCTYPE html>
<html>
<head>
  <title>HTTP Request From Form</title>
</head>
<body>
  <h1>JavaScript GET Request from Form</h1>
  <form id="requestForm">
    <label for="ipAddress">IP Address:</label>
    <input type="text" id="ipAddress" name="ipAddress" required>
    <label for="format">Format:</label>
    <select id="format" name="format">
      <option value="JSON">JSON</option>
      <option value="XML">XML</option>
    </select>
    <button type="submit">Send Request</button>
  </form>
  <script>
    // JavaScript code to handle form submission and send the request
  </script>
</body>
</html>

In the above code, we have added an HTML <form> element with two input fields: "ipAddress" and "format". The "ipAddress" field is a text input, and the "format" field is a dropdown menu. We also added a submit button.

Now, let's write the JavaScript code to handle the form submission and send the GET request. Here's an example of how the code should look:

var requestForm = document.getElementById("requestForm");
requestForm.addEventListener("submit", function(event) {
  event.preventDefault();

  var ipAddress = document.getElementById("ipAddress").value;
  var format = document.getElementById("format").value;

  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      var response = JSON.parse(this.responseText);
      // Handle the response accordingly
    }
  };
  var url = "URL" + "?ipAddress=" + ipAddress + "&format=" + format;
  request.open("GET", url, true);
  request.send();
});

In the above code, we use the addEventListener method to attach a "submit" event listener to the form. When the form is submitted, the event is triggered, and the specified callback function is executed. Inside the callback function, we prevent the default form submission behavior using event.preventDefault(). Then, we retrieve the values entered in the form fields using getElementById and store them in variables. These variables are used to construct the URL for the GET request. Finally, we send the GET request using the same code we used earlier.

Now, when the user enters an IP address and selects a format from the form, the code will send the GET request accordingly. The response will be handled inside the onreadystatechange event handler.

In this section, we learned how to send a GET request dynamically by passing parameters from a form. In the next section, we will explore how to send an HTTP POST request using JavaScript.

How to Send an HTTP POST Request Using JavaScript

To send an HTTP POST request using JavaScript, we need to follow a similar process as sending a GET request. However, there are a few key differences.

Let's start by understanding the basics of sending an HTTP POST request using JavaScript. Similar to sending a GET request, we can use the XMLHttpRequest object to make the request. However, in this case, we need to specify the request type as "POST" using the open method. Additionally, we need to set the Content-Type header to specify the format of the data being sent in the request body. Once the request is sent, we can handle the response in the same way as we did with GET requests.

To illustrate the process, we will use the HTTP Bin service, an open-source website that allows us to test different types of HTTP requests. We will focus on sending a POST request using a form value.

The HTTP Bin Service: Testing POST Requests

To test sending a POST request, we will be using the HTTP Bin client. This website provides a simple interface to send different types of HTTP requests and view the response. We will use it to send a POST request with form data and analyze the response.

To get started, follow these steps:

  1. Install the Postman add-on for Google Chrome.
  2. Open the Postman add-on.
  3. Create a new request using the HTTP Bin URL (https://httpbin.org/post).
  4. Specify the request type as "POST".
  5. Add form data to the request.
  6. Send the request and view the response.

I have already provided an example URL for you to test.

Now, let's move on to sending the same POST request using JavaScript.

Dynamic POST Requests using JavaScript

To send a POST request dynamically with form values, we need to modify our HTML page. Create a new HTML file, name it "HTTPPOSTOnload.html", and open it in a text editor. Add the basic HTML tags, similar to what we did for the GET request.

<!DOCTYPE html>
<html>
<head>
  <title>HTTP POST Onload</title>
</head>
<body>
  <h1>JavaScript POST Request Onload</h1>
  <script>
    // JavaScript code to send the POST request and get the response
  </script>
</body>
</html>

Inside the <script> tag, we will write the JavaScript code that handles the HTTP POST request. We will use the XMLHttpRequest object to make the request. Here's an example of how the code should look:

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    var response = JSON.parse(this.responseText);
    alert(response);
  }
};
request.open("POST", "URL", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("key1=value1&key2=value2");

In the above code, we create an instance of the XMLHttpRequest object and define the onreadystatechange event handler. Inside the event handler, we check if the request is completed (readyState === 4) and successful (status === 200). If the conditions are met, we parse the JSON response and display it using the alert function. The open method is used to specify the type of request ("POST" in this case) and the URL to which the request is sent. Additionally, we use the setRequestHeader method to set the "Content-Type" header to specify that We Are sending form data. Finally, we call the send method and pass the form data encoded as a STRING.

To test the code, simply open the HTML file in a browser. The page will send the HTTP POST request automatically on page load, and you should see the response displayed in an alert.

So far, we have learned how to send a POST request using JavaScript. However, what if we want to pass dynamic form values and display the response in the HTML page? Let's explore that next.

Dynamic POST Requests using JavaScript

To send a POST request with dynamic form values and display the response in the HTML page, we need to modify our HTML file once again. Create a new HTML file, name it "HTTPPOSTFromForm.html", and open it in a text editor. Add the basic HTML tags, similar to what we did for the GET request.

<!DOCTYPE html>
<html>
<head>
  <title>HTTP POST From Form</title>
</head>
<body>
  <h1>JavaScript POST Request From Form</h1>
  <form id="requestForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <button type="submit">Send Request</button>
  </form>
  <script>
    // JavaScript code to handle form submission and send the POST request
  </script>
</body>
</html>

In the above code, we have added an HTML <form> element with an input field for the name and a submit button.

Now, let's write the JavaScript code to handle the form submission and send the POST request. Here's an example of how the code should look:

var requestForm = document.getElementById("requestForm");
requestForm.addEventListener("submit", function(event) {
  event.preventDefault();

  var name = document.getElementById("name").value;

  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      var response = JSON.parse(this.responseText);
      // Handle the response accordingly
    }
  };
  var url = "URL";
  var formData = new FormData();
  formData.append("name", name);
  request.open("POST", url, true);
  request.send(formData);
});

In the above code, we use the addEventListener method to attach a "submit" event listener to the form. When the form is submitted, the event is triggered, and the specified callback function is executed. Inside the callback function, we prevent the default form submission behavior using event.preventDefault(). Then, we retrieve the value entered in the "name" field using getElementById and store it in a variable. We create a FormData object to store the form data and append the form values using the append method. Finally, we send the POST request using the same code we used earlier.

Now, when the user enters a name in the form and submits it, the code will send the POST request with the form data. The response will be handled inside the onreadystatechange event handler.

In this section, we learned how to send a POST request dynamically by passing form values. We explored how to retrieve dynamic values from a form and send them as form data.

Summary

In this article, we covered the process of sending HTTP GET and POST requests using JavaScript. We learned how to create a simple HTML page and use the XMLHttpRequest object to make the requests. We explored how to send a GET request with default parameters, dynamically pass parameters using a form, and handle the responses. We also looked at how to send a POST request, both with static and dynamic form data, and display the responses.

Conclusion

Sending HTTP GET and POST requests using JavaScript is an essential skill for web developers. It allows us to Interact with APIs and retrieve or submit data from/to a server. By understanding the basics of handling HTTP requests in JavaScript, you can enhance the functionality of your web applications and provide a better user experience.

Most people like