DEV Community

Cover image for AJAX - Calling JSON api using XML in CodePen
Muhammad Asif
Muhammad Asif

Posted on

AJAX - Calling JSON api using XML in CodePen

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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Preview
Without click

Image description

After button is clicked

Image description

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');
Enter fullscreen mode Exit fullscreen mode

First, Clear the console. Then catch the button and p element by their id.

btn.addEventListener('click', getData);
Enter fullscreen mode Exit fullscreen mode

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();

}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Then we have to send this request by send() function in the bottom.

xhr.send();
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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>
   `
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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/'
Enter fullscreen mode Exit fullscreen mode

CodePen

The entire project is in CodePen

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
Portfolio

Top comments (0)