Calling REST web service using Ajax with JavaScript

Fri, Nov 15, 2019

Read in 1 minutes

Using Ajax you can make REST API calls in an asynchronous way. Ajax stands for Asynchronous JavaScript XML. In this article, you can explore how to make ‘get’ request with rest API using AJAX and for this article, https://reqres.in/ demo web services have been used.

XMLHttpRequest API is used for making this an asynchronous call.

Steps to make Ajax call :

javascriptAJAXcall

<html>
      <head>
      </head>
      <body>
              <table>
                  <tr><td> Enter product id <input type="text" id="productID"></td></tr>
                  <tr><td>  <button type="submit"style="width:90px;height:22px"
                      onclick="getProductDetails();"> click</button></td></tr>
              </table>
      <script>
             function  getProductDetails(){
              var productID=document.getElementById("productID").value;
              const Http = new XMLHttpRequest();
              const url=`https://reqres.in/api/products/${productID}`;
              console.log("url=="+url);
              Http.open("GET", url);
              Http.send();
              Http.onreadystatechange=function(){
                  if(this.readyState==4 && this.status==200){
              console.log(Http.responseText)
                  }
              }
          }
          </script>
      </body>
  </html>

javascriptAjaxcall1