How to call web services in HTML5 ?
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.
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.
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:// ).
Note: This only works for safe URL which is supported by CORS policy and does not work for file:// protocol
Please Login to comment...