AJAX - Calling JSON api using XML in CodePen
Tags: webdev, javascript, ajax, api
Published: 2022-01-09 14:21:01

In this article, we are going to work on AJAX XMLHttpRequest into a easiest way. It can fetch single post and entire post by calling json api data. Also we will use some html, CSS, JavaScript First, Let's see what are we building.

##Requirements
1. HTML
2. CSS
3. JavaScript(DOM, AJAX, API)

So, let's jump into the project

##HTML
```
<body>
 <button id="btn">Get Data</button>
  <p id="p"></p>
</body>
```
In HTML section, we create a button and below it we put a 'p' text which will display the data, when we will click on the 'button'.

first of all, setting the window bar
##CSS
```
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body{
  background: lightblue;
}
```
Let's design the button and ui kit with CSS.

```
button{
  padding: 10px 30px;
  text-transform: capitalize;
  background: #222;
  color: #eee;
  outline: 0;
  border: 0;
  border-radius: 3px;
  cursor: pointer;
  text-align: center;
  margin: 20px 10px;
}
button:active{
  transform: scale(0.97);
}
```
The button is ready to use now. When the button will be clicked the 'p' text will display the JSON data. It will convert as 'ul li' unordered list style.

```
ul {
  background: firebrick;
  padding: 20px;
  margin: 0 10px
}
ul li{
  color: lightblue;
}
```
Preview
Without click

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qkp8dp3yulilzbqcej1l.PNG)

After button is clicked

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4bagosz5jjddgdos9xx4.PNG)

##Javascript

```
console.clear();
// external json data from codepen 'https://codepen.io/nakome/pen/DnEvr'
// fake api data 'https://jsonplaceholder.typicode.com/posts/'
const btn = document.getElementById('btn');
const p = document.getElementById('p');
```
First, Clear the console. Then catch the button and p element by their id.

```
btn.addEventListener('click', getData);
```
Added 'click' Event Listener to btn and creates a function name 'getData'

```
function getData (){
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
  // xhr.open('GET', 'https://codepen.io/nakome/pen/DnEvr.js', true);
  xhr.onload = function(){
    if(this.status == 200){
      const data = JSON.parse(this.responseText)
   p.innerHTML = `
   <ul>
   <li>ID: ${data.id}</li>
   <li>Title: ${data.title}</li>
   <li>Body: ${data.body}</li>
   </ul>
   `
    }
  }
  xhr.onerror = function(){
    const error = `404: Not Found`
    console.log(error);
    p.innerHTML = error;
  }
  xhr.send();
  
}
```
we put the XMLHttpRequest to a variable name 'xhr'. then 'open' function take three parameter 'method', 'url/fileName', 'true/false'.

```
const xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
```
Then we have to send this request by send() function in the bottom.

```
xhr.send();
```
Now, to get the api data we have to use a event name 'onload'. here we make a conditional, if status is equal to 200 then the data will be received. The data is received by responseText method. when we will use the server data we have convert it by json.parse method. And we put this value into the new variable name 'data'.

```
 xhr.onload = function(){
    if(this.status == 200){
      const data = JSON.parse(this.responseText)
```
Here, I used template literal for a clean code. The 'data' are called by their id, title and body name in dot notation method.
```
p.innerHTML = `
   <ul>
   <li>ID: ${data.id}</li>
   <li>Title: ${data.title}</li>
   <li>Body: ${data.body}</li>
   </ul>
   `
```
At last, I create an error function if there is an error.

```
xhr.onerror = function(){
    const error = `404: Not Found`
    console.log(error);
    p.innerHTML = error;
```
##Notes
Here, I have put two different types of json api. I worked on fake api. You can work both of these.

```
// external json data from CodePen - 'https://codepen.io/nakome/pen/DnEvr'
// fake api data - 'https://jsonplaceholder.typicode.com/posts/'
```
##CodePen
[The entire project is in CodePen](https://codepen.io/CODER_ASIF/pen/gOGdWpq?editors=1111)

##Wrapping Up
I hope you enjoyed the article, if yes then don't forget to press ❤️ and Subscribe. You can also bookmark it for later use. It was fun to make this project and If you have any queries or suggestions don't hesitate to drop them. See you.
You can extend your support by giving me stars on GitHub Profile.😊👇
[Github](https://github.com/Mohammad-Asif-Web)
[Portfolio](https://muhammadasif10.blogspot.com/)