DEV Community

Chinmay Agrawal
Chinmay Agrawal

Posted on

Make API Calls Using XMLHttpRequest : AJAX

XMLHttpRequest object is used to send and receive data from server. In other words it is used to communicate to the server.

Today in this article we are going to know how to fetch data from the source(text file/JSON file/API) by making calls using xmlhttprequest object, and that too asynchronously. Yes this xmlhttprequest object make calls asynchronously means the user can do other task while this object is fetching data. So you will get the knowledge of what called AJAX i.e. Asynchronous JavaScript XML.

Disclaimer: This blog is specifically for absolute beginners. And also this should be noted that in today's modern era this method is not used too much to make api calls, instead more modern methods like fetch() or axios are used. But as a beginner, as i always recommend, your foundations should be clear. So by this article you will get the knowledge of fetching data from different sources, and after that you can apply this knowledge to study other modern methods.

🚀Setting up environment 🚀

Now first make folder structure like this:

ajax folder structure for fetching data by XMLHttpRequest Object

So as of now we have 4 files in our folder and each file looks like this👇

html file for inserting data in webpage by ajax

js file for fetching data from file by ajax

text file for fetching data from it by ajax

json file for fetching data from it by ajax

  • In index.html file we will insert data in the h1 tag when button is clicked.
  • In script.js file we will write code for fetching data from various files using XMlHttpRequest.
  • data.txt and data.json are the source files from where we will fetch data.

So, now what we are going to do is, we will fetch data from the text & JSON files and display that data into the webpage. Also later in the blog we will also make API calls to GET & POST data.

To use XMLHttpRequest() object we need to follow the following 4 basic steps. We will follow these steps throughout this tutorial:

  • Make XMLHttpRequest() object.
  • Open file and specify request method.
  • Send request
  • Handle the response which we receive.

👨‍💻 Fetch Data from Text File

In the real world scenario we don't generally need to fetch data from the text files. But still I am explaining it here so that you will get the foundations clear of XMLHttpRequest object.
So you should pay attention to this section as in this we will discuss the basics of xmlhttprequest and how to use it.

// capture the button by using its id and add a eventlistner to it
document.getElementById("ajaxdata").addEventListener("click", getData)

//capture the element in which we will insert the data
let el = document.getElementById("head")

//function definition for our event handling
function getData(){
    console.log("button clicked")
    const xhr = new XMLHttpRequest(); // make object of XMLHttpRequest
    xhr.open('GET', 'data.txt')
    xhr.send();
    xhr.onload = () => {
        if(xhr.status === 200){
            el.innerText = xhr.response
        } else {
            console.log('no data received')
        }
    };
}
Enter fullscreen mode Exit fullscreen mode

In the above code first we are creating object xhr of XMLHttpRequest() to do various operations on it. Now after creating object we will use this object to perform various operations.

Now to target the file from which we want to fetch the data(data.txt in our case). We have xhr.open() method to open a file. It takes two mandatory parameters

  • first one is method of request it can be 'GET', 'POST', 'PUT', 'DELETE', etc.
  • Second is the location of file from which we have to fetch data.

After targeting the file, we will send the request using xhr.send() method.

After sending request we will handle the response which we receive. For this we will use xhr.onload() method.
After receiving request first we will check the status of request that if the request is success or not with the help of xhr.status. If status contained 200 then we can proceed further otherwise we can return some error message.

Now if receive xhr.status == 200 then we can proceed with our received data. Now we just have to inject the received data into the html page. So the data which we receive from xhr object can be accessed by xhr.respone method.

If you know the little bit of JavaScript then this will be very easy task for you. You just have to add this line to the code
el.innerText = xhr.response.

Now save the files and open the index.html with live server(if you are using VScode). And click on the Get Data button. And Hurray!!!🚀🚀...you make your first http request

Text output from ajax

👨‍💻 Fetch Data from JSON File

So now as you know how to fetch data from text file, you can easily do the same for JSON files also with just tiny tweaks. Let me directly show you the code.

// capture the button by using its id and add a eventlistner to it
document.getElementById("ajaxdata").addEventListener("click", getData)

//capture the element in which we will insert the data
let el = document.getElementById("head")

//function definition for our event handling
function getData(){
    console.log("button clicked")
    const xhr = new XMLHttpRequest(); // make object of XMLHttpRequest
    xhr.open('GET', 'data.json')
    xhr.responseType = "json"
    xhr.send();
    xhr.onload = () => {
        if(xhr.status === 200){
            el.innerText = xhr.response.name
        } else {
            console.log('no data received')
        }
    };
}
Enter fullscreen mode Exit fullscreen mode

In the above code we have changed the filename to data.json and also added this new line: xhr.responseType = "json"
The purpose of this line is to convey that the data which we are receiving should be converted from JSON to JavaScript object.

And now we can access the data as normally as we access the JS Object, by using the key of the data.

Now you can test the above code in browser and you will get the data in your webpage.

👨‍💻 Get Data from API

Now we are heading to the main Section of the Blog. We are going to make API calls. For the purpose of this tutorial we are going to use this fake API to GET the data https://jsonplaceholder.typicode.com/posts/1

This above API Link gives the following response:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Enter fullscreen mode Exit fullscreen mode

As we know, how to fetch data from JSON file, it is going to be super easy for us to make API calls. So lets directly jump into the code.

// capture the button by using its id and add a eventlistner to it
document.getElementById("ajaxdata").addEventListener("click", getData)

//capture the element in which we will insert the data
let el = document.getElementById("head")

//function definition for our event handling
function getData(){
    console.log("button clicked")
    const xhr = new XMLHttpRequest(); // make object of XMLHttpRequest
    xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1')
    xhr.responseType = "json"
    xhr.send();
    xhr.onload = () => {
        if(xhr.status === 200){
            el.innerText = xhr.response.body
        } else {
            console.log('no data received')
        }
    };
}
Enter fullscreen mode Exit fullscreen mode

From the above code you can see that we just have minor changes like, instead of file name we have given the URL of API.
And we are using the received data according to our need(Here I am showing you to use only body value, and I hope you can use the other also according to your need).

Now you can test the above code in your browser.

👨‍💻 POST Data to API

Until now we studied how to get the data. But in real world application we also need to send some data to the server. So for this we need to make POST request to the API.
For this tutorial we are going to use this dummy API https://dummy.restapiexample.com/api/v1/create

This accepts data in the following format:

{"name":"geek","salary":"404","age":"23"}
Enter fullscreen mode Exit fullscreen mode

And in success response we get:

{
    "status": "success",
    "data": {
        "name": "test",
        "salary": "123",
        "age": "23",
        "id": 25
    }
}
Enter fullscreen mode Exit fullscreen mode

So we will POST the data to the API. So without wasting any further time let directly jump into the code.

// capture the button by using its id and add a eventlistner to it
document.getElementById("ajaxdata").addEventListener("click", getData)

//capture the element in which we will insert the data
let el = document.getElementById("head")

//function definition for our event handling
function getData(){
    console.log("button clicked")
    const xhr = new XMLHttpRequest(); // make object of XMLHttpRequest
    xhr.open('POST', 'https://dummy.restapiexample.com/api/v1/create')
    xhr.responseType = "json"
    mydata = '{"name":"test","salary":"123","age":"23"}'
    xhr.send(mydata);
    xhr.onload = () => {
        if(xhr.status === 200){
            el.innerText = xhr.response.status
        } else {
            console.log('no response received')
        }
    };
}
Enter fullscreen mode Exit fullscreen mode

Here we have a variable mydata which contains the data which we want to send. And we are passing this variable in xhr. send() method. So that when making the request we can sent the data also.

When you run the above code you will get the success message displayed in browser. Which shows the data is saved into your browser.
Also one thing to noted is that in the given example we are manually sending data, but in real world scenarios the data generally comes from the form so with little bit of JavaScript you can easily do that too.

👨‍💻 Conclusion

We have covered all the primary topics in the blog that are needed to work with XMLHttpRequest() These are enough for you to get started with world of AJAX. You know how to:

  • Get the data from text file.
  • Get the data from JSON file.
  • Get the data from API.
  • Post the data to API.

But remember, this XMLHttpRequest is slowly loosing its popularity. As we have now more modern methods to make API calls such as fetch() or axios. If you want me to write articles on modern methods then tell me in comment section. I will write the blog on it.

Top comments (0)