Open In App

How to call web services in HTML5 ?

Last Updated : 14 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to call the Web Services in HTML5, along with knowing different methods for calling the web services & understand them through the examples.

Web services in HTML5 are a set of open protocols and standards that allow data to be exchanged between different applications or systems. This helps an application to share some information with other applications through the internet.

Procedure for calling the Web Services: Calling of web services can be done using the in-built web API’s and the browser provides you two different API’s which are:

  • XMLHttpRequest: XMLHTTPRequest object is an API that is used for fetching data from the server. It is basically used in Ajax programming. It retrieves any type of data such as JSON, XML, text, etc. It requests data in the background and updates the page without reloading the page on the client side.
  • Fetch API: The Fetch API provides the fetch() method defined on a window object. This is used to perform requests. This method returns a Promise which can be further used to retrieve the response to the request. 

The concept on which web services can be called from HTML is called AJAX (Asynchronous XML and Javascript), which was introduced in the year 2005 by Jesse James Garrett. Using this we can update our HTML structure without any page load. This makes an HTTP request to the web service without blocking the DOM.

We will explore both these concepts to call web services by making use of the XMLHttpRequest or Fetch API.

XMLHttpRequest Object: To make a request to the web service, we need to create an instance of XMLHttpRequest just by following the below steps:

  • Create XMLHttpRequest object
  • Listen to the web service response using onload event
  • Open the http request using open( ) method
  • Send the request

Example 1: In this example, we will make a request to the free web service called as JSONPlaceholder. Now, create an HTML file and copy the below code and then open the file in a browser with a live server.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <meta name="viewport" 
          content='width=device-width, 
                         initial-scale=1.0'>
    <title>Calling the Web Services in HTML5</title>
</head>
  
<body style="text-align:center">
    <h1 style="color:green">GeekforGeeks</h1>
    <h3>Calling the Web Services in HTML5</h3>
    <script>
        var xhr = new XMLHttpRequest( );
        xhr.onload = (res)=>{
           if(res.target.status == 200){
             document.body.innerHTML += 
             (res.target.responseText);
           }
        }
        xhr.open("GET",".../todos/1",true);
        xhr.send();
    </script>
</body>
  
</html>


Output: The above code will display the response on the document. Here, we run the code with the live server at URL 127.0.0.1:5501/fetch.html

 

Fetch API: The Fetch API provides an interface for fetching resources. It is similar to XMLHTTPRequest, but this API provides a more powerful and flexible feature. The steps are given below:

  • Create a fetch request with fetch( ) method
  • This returns a promise so add a promise handler then( )
  • Using catch( ) you can handle the failure

Example 2: In this example, we will make a request to the free web service called as JSONPlaceholder. Now, create an HTML file and copy the below code and then open the file in a browser with the live server ( The URL should not start with the file:// ).

HTML




<!DOCTYPE html>
<html>
  
<head>
  <meta name="viewport" 
        content='width=device-width, 
                 initial-scale=1.0'>
  <title>Calling the Web Services in HTML5</title>
</head>
  
<body style="text-align:center">
  <h1 style="color:green">GeekforGeeks</h1>
  <h3>Calling the Web Services in HTML5</h3>
  <script>
    fetch('.../todos/1')
      .then((res) => {
        return res.text()
      }).then((data) => {
        document.body.innerHTML +=
        (data)
      })
      .catch((err) => console.debug(err));
  </script>
</body>
  
</html>


Output:

 

Note: This only works for safe URL which is supported by CORS policy and does not work for file:// protocol



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads