Working with AJaX JSON
Tags: beginners, javascript, json, tutorial
Published: 2020-01-17 09:41:26

- IF YOU ARE NEW TO THIS ARTICLE, I RECOMMEND TO READ "Introduction To Asynchronous JavaScript" and "XmlHttpRequest (XHR) Object Request" ARTICLE BEFORE STARTING THIS.

- [Introduction To Asynchronous JavaScript](https://dev.to/mihinduranasinghe/introduction-to-asynchronous-javascript-351a)

- [XmlHttpRequest (XHR) Object Request](https://dev.to/mihinduranasinghe/xmlhttprequest-xhr-object-request-34dj)

---------------------------------------------------------------------

##**Here we are going to GET some data from a .JSON file and display them in a simple web page**

There are two types of data in a json file to GET

- Get single object data from a json file
- Get multiple data from an array of a json file (fetching an array)

###Note:
- We have created a ***customer.json*** file with a single customer's data

```json
{
    "id": 1,
    "name": "Mihindu ranasinghe",
    "company": "CyberCatsIT",
    "phone": "11-222-555"
} 
```
- We have created a ***customers.json*** file with a multiple customers' data

```json
[

{
    "id": 1,
    "name": "Mihindu ranasinghe",
    "company": "CyberCatsIT",
    "phone": "11-222-555"
},

{
    "id": 2,
    "name": "Kavindu ranasinghe",
    "company": "CyberCatsIT",
    "phone": "11-222-555"
},

{
    "id": 3,
    "name": "Supun ranasinghe",
    "company": "CyberCatsIT",
    "phone": "11-222-555"
} 

]
```

- And a simple web page with two buttons as "Get Customer" and "Get Customers".

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" integrity="sha256-ECB9bbROLGm8wOoEbHcHRxlHgzGqYpDtNTgDTyDz0wg=" crossorigin="anonymous" />

    <title>Document</title>
</head>
<body>
   <div class="container">

       <button id="button1">Get Customer</button>
       <button id="button2">Get Customers</button>
       <br><br>
       <div class="" id="output"></div>
       <h2>Customer</h2>
       <div class="" id="customerOutput"></div>

       <h2>Customers</h2>
       <div class="" id="customersOutput"></div>
   </div> 
<script src="app.js"></script>
</body>
</html>
```

####👏👏***Let's code the JavaScript part - app.js***...


- Get single object data from the ***customer.json*** file

```javascript
document.getElementById('button1').addEventListener('click',loadCustomer);

//Load single customer
function loadCustomer(e){
    const xhr = new XMLHttpRequest();
    xhr.open('GET','customer.json',true);

    xhr.onload = function(){
        if(this.status === 200){//Check Http status is Ok or not
            //Display on console
            console.log(this.responseText);

            //Displaying on web
              const customer = JSON.parse(this.responseText);
          
              const output = `
                <ul>
                    <li>ID: ${customer.ID} </li>
                    <li>Name: ${customer.name} </li>
                    <li>Company: ${customer.company} </li>
                    <li>Phone: ${customer.phone} </li>
                </ul>
            `;

            document.getElementById('customerOutput').innerHTML = output;

            
        }
    }
    xhr.send();

```
- Get multiple data from an array of a ***customers.json*** file (fetching an array)

```javascript
document.getElementById('button2').addEventListener('click',loadCustomers);

//load ustomers
function loadCustomers(e){
    const xhr = new XMLHttpRequest();
    xhr.open('GET','customers.json',true);

    xhr.onload = function(){
        if(this.status === 200){//Check Http status is Ok or not

            //Displaying on web
             const customers = JSON.parse(this.responseText);
            let output = '';
            customers.forEach(function(customer){
                output += `
                <ul>
                    <li>ID: ${customer.id} </li>
                    <li>Name: ${customer.name} </li>
                    <li>Company: ${customer.company} </li>
                    <li>Phone: ${customer.phone} </li>
                </ul>
            `;

            });
            
        document.getElementById('customersOutput').innerHTML = output;

            
        }
    }
    xhr.send();
}
```
**You can do those two functions in a single app.js file**.

*Output*
![OutPut](https://thepracticaldev.s3.amazonaws.com/i/ji87ezih0l438nsso7hb.PNG)

####👏👏**This works in the similar way if you are fetching something from an external URL from a public API. For example, getting the github users from their public API. **
*In this case we are using a local json file*

👉What's Next?
IF YOU HAVE DONE READING "Working with AJaX JSON" ARTICLE, I SUGGEST YOU TO READ MY NEXT ARTICLE.

- [How to use external API?]()

##**Thank You**

***Hope you all enjoyed and learned something on this. Please let me know your comments suggestions and any questions you have about this blog***.

👉 Visit me - [https://mihinduranasinghe.com/](https://mihinduranasinghe.com/)