How to use simple API using AJAX ? - GeeksforGeeks

03 Jun, 2020
AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX.
Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here.
What are basic building?We will be fetching employee’s names from an employee object from a free API and displaying them inside a list. There are many API available for free on the internet. You can use any one of them.
HTML Code: We have a button and to fetch data and an empty unordered list inside which we will be adding our list-items dynamically using JavaScript.
<!DOCTYPE html><html lang="en">  <head>    <!-- Required meta tags -->    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width,        initial-scale=1, shrink-to-fit=no" />      <!-- Bootstrap CSS -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"        crossorigin="anonymous" />      <title>        How to use simple API using AJAX ?    </title></head>  <body>    <button type="button" id="fetchBtn"        class="btn btn-primary">        Fetch Data    </button>      <div class="container">        <h1>Employee List</h1>        <ul id="list"></ul>    </div>      <!-- Optional JavaScript -->    <!-- jQuery first, then Popper.js,         then Bootstrap JS -->    <script src="Ajax.js"></script>    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"        crossorigin="anonymous">    </script>          <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"        crossorigin="anonymous">    </script>          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"        crossorigin="anonymous">    </script></body>  </html>
AJAX Code:
Step 1: The first step is to get the button element getElementById method.
Step 2: The second step is to add an eventListener to the the button and providing a call-back function to it.
Step 3: Instantiate an XHR object using new keyword.
Step 4: Open an object using open function. It takes three parameters, the first one is type (GET or POST), second is the URL for the API and last one is a boolean value (true means asynchronous call and false means synchronous call).
Step 5: Now we will use onload function to display the data. The onload function is executed after the API call is done. We will check for the status of success. We are checking it with 200 as 200 is the success code for an HTTP request.
Step 6: Now, we will use parse it into a JSON object so that we can easily fetch data from it.
Step 7: In this step, we will use a loop to iterate over all the items in the object and adding it to the list using innerhtml property.
Step 8: Last step is to send the request using the send() function.Below is the implementation of the above steps. We have also provided comments in each line for making the code easy to understand.<script>    let fetchBtn = document.getElementById("fetchBtn");        fetchBtn.addEventListener("click", buttonclickhandler);      function buttonclickhandler() {          // Instantiate an new XHR Object        const xhr = new XMLHttpRequest();          // Open an obejct (GET/POST, PATH,        // ASYN-TRUE/FALSE)        xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true);                // When response is ready        xhr.onload = function () {            if (this.status === 200) {                  // Changing string data into JSON Object                obj = JSON.parse(this.responseText);                  // Getting the ul element                let list = document.getElementById("list");                str = ""                for (key in obj.data) {                    str += `<li>${obj.data[key].employee_name}</li>`;                }                list.innerHTML = str;            }            else {                console.log("File not found");            }        }          // At last send the request        xhr.send();    }</script>Complete Code: It is the combination of the above two code sections.<!DOCTYPE html><html lang="en">  <head>      <!-- Required meta tags -->    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width,            initial-scale=1, shrink-to-fit=no" />      <!-- Bootstrap CSS -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"        crossorigin="anonymous" />      <title>        How to use simple API using AJAX ?    </title></head>  <body>    <button type="button" id="fetchBtn"            class="btn btn-primary">        Fetch Data    </button>      <div class="container">        <h1>Employee List</h1>        <ul id="list"></ul>    </div>      <!-- Optional JavaScript -->    <!-- jQuery first, then Popper.js,         then Bootstrap JS -->    <script>        let fetchBtn = document.getElementById("fetchBtn");          fetchBtn.addEventListener("click", buttonclickhandler);          function buttonclickhandler() {              // Instantiate an new XHR Object            const xhr = new XMLHttpRequest();              // Open an obejct (GET/POST, PATH,            // ASYN-TRUE/FALSE)            xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true);                    // When response is ready            xhr.onload = function () {                if (this.status === 200) {                      // Changing string data into JSON Object                    obj = JSON.parse(this.responseText);                      // Getting the ul element                    let list = document.getElementById("list");                    str = ""                    for (key in obj.data) {                        str +=                         `<li>${obj.data[key].employee_name}</li>`;                    }                    list.innerHTML = str;                }                else {                    console.log("File not found");                }            }            xhr.send();        }    </script>      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"        crossorigin="anonymous">    </script>          <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"        crossorigin="anonymous">    </script>          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"        crossorigin="anonymous">    </script></body>  </html>Output:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.My Personal Notes
arrow_drop_upSave
Below is the implementation of the above steps. We have also provided comments in each line for making the code easy to understand.
<script>    let fetchBtn = document.getElementById("fetchBtn");        fetchBtn.addEventListener("click", buttonclickhandler);      function buttonclickhandler() {          // Instantiate an new XHR Object        const xhr = new XMLHttpRequest();          // Open an obejct (GET/POST, PATH,        // ASYN-TRUE/FALSE)        xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true);                // When response is ready        xhr.onload = function () {            if (this.status === 200) {                  // Changing string data into JSON Object                obj = JSON.parse(this.responseText);                  // Getting the ul element                let list = document.getElementById("list");                str = ""                for (key in obj.data) {                    str += `<li>${obj.data[key].employee_name}</li>`;                }                list.innerHTML = str;            }            else {                console.log("File not found");            }        }          // At last send the request        xhr.send();    }</script>
Complete Code: It is the combination of the above two code sections.
<!DOCTYPE html><html lang="en">  <head>      <!-- Required meta tags -->    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width,            initial-scale=1, shrink-to-fit=no" />      <!-- Bootstrap CSS -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"        crossorigin="anonymous" />      <title>        How to use simple API using AJAX ?    </title></head>  <body>    <button type="button" id="fetchBtn"            class="btn btn-primary">        Fetch Data    </button>      <div class="container">        <h1>Employee List</h1>        <ul id="list"></ul>    </div>      <!-- Optional JavaScript -->    <!-- jQuery first, then Popper.js,         then Bootstrap JS -->    <script>        let fetchBtn = document.getElementById("fetchBtn");          fetchBtn.addEventListener("click", buttonclickhandler);          function buttonclickhandler() {              // Instantiate an new XHR Object            const xhr = new XMLHttpRequest();              // Open an obejct (GET/POST, PATH,            // ASYN-TRUE/FALSE)            xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true);                    // When response is ready            xhr.onload = function () {                if (this.status === 200) {                      // Changing string data into JSON Object                    obj = JSON.parse(this.responseText);                      // Getting the ul element                    let list = document.getElementById("list");                    str = ""                    for (key in obj.data) {                        str +=                         `<li>${obj.data[key].employee_name}</li>`;                    }                    list.innerHTML = str;                }                else {                    console.log("File not found");                }            }            xhr.send();        }    </script>      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"        crossorigin="anonymous">    </script>          <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"        crossorigin="anonymous">    </script>          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"        crossorigin="anonymous">    </script></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
jQuery-AJAX
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)