How to call web services in HTML5?


Introduction

Calling web services is one of the most commonly used services over the web. It refers to the way of communicating with the software systems. This communication can be between the clients with the server, peer-to-peer, etc. HTML5, the latest version of HTML, provides A LOT OF WAYS LIKE XMLHttpRequest object, APIs like Axios and fetch, WebSockets, etc. This API allows the users to get dynamic static, real-time, or dynamic content depending upon the requirement.

In this article, we shall learn how to call web services by using different methods like calling APIs, web sockets, etc.

XMLHttpRequest

is a popular choice for developers because of its wide range of flexibility and advantages. It allows updating the page without reloading which is widely used in applications like chatting, news, etc. It allows the client's computer to request data after a particular page has been loaded. This allows the web pages to be highly dynamic. Additionally, the client computer can also send data to the server in the background while the page is being displayed.

Example

<!DOCTYPE html>
<html lang="en">
<body>
   <div id="data"></div>
   <script>
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "https://reqres.in/api/users?page=2", true);
      xhr.onreadystatechange = function () {
         if (this.readyState === 4 && this.status === 200) {
            var response = JSON.parse(this.responseText);
            var dataDiv = document.getElementById("data");
            dataDiv.innerHTML = JSON.stringify(response);
         }
      };
      xhr.send();
   </script>
</body>
</html>

Explanation

  • This HTML code fetches data from the web service API located at "https://reqres.in/api/users?page=2". The JavaScript code sends an XMLHttpRequest to this API and waits for a response.

  • If the response is successful (i.e., with status 200), it is parsed as JSON and displayed in the HTML document by setting the innerHTML of a <div> element with the ID "data". This results in the data being displayed on the webpage.

Fetch API

The Fetch API is a modern replacement for the XMLHttpRequest object. It provides a simpler and more powerful way to call web services. The Fetch API is based on promises and supports both REST and SOAP web services.

Example

<!DOCTYPE html>
<html lang="en">
<body>
   <table id="data-table">
      <thead>
         <tr>
            <th>ID</th>
            <th>Email</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Avatar</th>
         </tr>
      </thead>
      <tbody></tbody>
   </table>
   <script>
      fetch("https://reqres.in/api/users?page=2")
      .then((response) => response.json())
      .then((data) => {
         var dataTable = document.getElementById("data-table");
         var tbody = dataTable.getElementsByTagName("tbody")[0];
         data.data.forEach((user) => {
            var row = document.createElement("tr");
            var idCell = document.createElement("td");
            idCell.innerHTML = user.id;
            var emailCell = document.createElement("td");
            emailCell.innerHTML = user.email;
            var firstNameCell = document.createElement("td");
            firstNameCell.innerHTML = user.first_name;
            var lastNameCell = document.createElement("td");
            lastNameCell.innerHTML = user.last_name;
            var avatarCell = document.createElement("td");
            avatarCell.innerHTML = "<img src='" + user.avatar + "' />";
            row.appendChild(idCell);
            row.appendChild(emailCell);
            row.appendChild(firstNameCell);
            row.appendChild(lastNameCell);
            row.appendChild(avatarCell);
            tbody.appendChild(row);
         });
      });
   </script>
</body>
</html>

Explanation

This code fetches data from the web service URL "https://reqres.in/api/users?page=2" using the fetch API. Then, it creates a table with columns for ID, Email, First Name, Last Name, and Avatar, and populates the table with the data fetched from the URL using the DOM manipulation methods. Finally, it displays the table on the web page.

WebSockets API

The WebSockets API is a bidirectional communication protocol that enables real-time communication between the client and the server. The WebSockets API is useful for applications that require real-time updates, such as chat applications and online gaming.

Open a folder in VS code and run the following command in the terminal −

yarn add ws
or
npm install ws

Now create a JavaScript file say index.js

Add the following code there −

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
   console.log('WebSocket connection established.');

   ws.on('message', function incoming(message) {
      console.log(`Received message: ${message}`);
      ws.send(`You said: ${message}`);
   });

   ws.on('close', function close() {
      console.log('WebSocket connection closed.');
   });

   ws.on('error', function error(err) {
      console.error('WebSocket error:', err);
   });
});

Run the code.

Create an HTML file that says “index.html” and the following code there −

<!DOCTYPE html>
<html lang="en">
<body>
   <script>
      const socket = new WebSocket("ws://localhost:8080");
      socket.addEventListener("open", (event) => {
         console.log("WebSocket connection established.");
         socket.send("Hello, server!");
         const body = document.querySelector("body");
         const message = document.createElement("p");
         message.textContent = "WebSocket connection established!";
         body.appendChild(message);
      });
      socket.addEventListener("message", (event) => {
         console.log(`Received message: ${event.data}`);
      });
      socket.addEventListener("close", (event) => {
         console.log("WebSocket connection closed.");
      });
      socket.addEventListener("error", (event) => {
         console.error("WebSocket error:", event.error);
      });
   </script>
</body>
</html>

You will get the following message if the connection is successful −

WebSocket connection established!

Explanation

  • The JavsScript code here is to interact with the server. It establishes a connection in port number 8080. We have defined four functions namely connection, incoming, close, and error depending upon the lifecycle methods.

  • Next, we made the HTML file where we first established a connection with the localhost port 8080. If we have successfully established the connection we have displayed the success message in the front end.

Conclusion

In HTML5, web services can be called using JavaScript APIs such as XMLHttpRequest or Fetch API, allowing developers to make HTTP requests to retrieve and process data in various formats. This enables the creation of dynamic web pages that can interact with external services and databases. However, the method one should choose depends upon the specific requirements of the developers.

Updated on: 17-Apr-2023

869 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements