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.
- 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.
- ReactJS | AJAX and API
- Ajax | Introduction
- AJAX full form
- jQuery | ajax() Method
- How to set timeout for ajax by using jQuery?
- Difference Between JSON and AJAX
- Asynchronous file transfer in AJAX
- How ajax works? Difference between angular js and jquery
- Get request using AJAX by making Custom HTTP library
- POST request using AJAX by making Custom HTTP library
- How to display search result of another page on same page using ajax in JSP?
- Dockerizing a simple Nodejs app
- How to add API function to a simple PHP Page ?
- Making a simple PWA under 5 minutes
- Web Scrapping in PHP Using Simple HTML DOM Parser
- Simple POST request using the fetch API
- Flask - (Creating first simple application)
- Creating a simple JSON based API using Node.js
- NodeJS | Building simple REST API in express
- How to Make, Save, and Run a Simple VBScript Program?
Below is the implementation of the above steps. We have also provided comments in each line for making the code easy to understand.
Complete Code: It is the combination of the above two code sections.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.