Open In App
Related Articles

How to use simple API using AJAX ?

Like Article
Save Article
Report issue

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">
    <!-- 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=
        crossorigin="anonymous" />
        How to use simple API using AJAX ?
    <button type="button" id="fetchBtn"
        class="btn btn-primary">
        Fetch Data
    <div class="container">
        <h1>Employee List</h1>
        <ul id="list"></ul>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js,
         then Bootstrap JS -->
    <script src="Ajax.js"></script>
    <script src=
    <script src=
    <script src=


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 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.

Last Updated : 15 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Similar Reads