DEV Community

Cover image for Working with AJaX JSON
Mihindu Ranasinghe
Mihindu Ranasinghe

Posted on • Updated on

Working with AJaX JSON


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
{
    "id": 1,
    "name": "Mihindu ranasinghe",
    "company": "CyberCatsIT",
    "phone": "11-222-555"
} 
Enter fullscreen mode Exit fullscreen mode
  • We have created a customers.json file with a multiple customers' data
[

{
    "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"
} 

]
Enter fullscreen mode Exit fullscreen mode
  • And a simple web page with two buttons as "Get Customer" and "Get Customers".
<!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>
Enter fullscreen mode Exit fullscreen mode

πŸ‘πŸ‘Let's code the JavaScript part - app.js...

  • Get single object data from the customer.json file
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();

Enter fullscreen mode Exit fullscreen mode
  • Get multiple data from an array of a customers.json file (fetching an array)
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();
}
Enter fullscreen mode Exit fullscreen mode

You can do those two functions in a single app.js file.

Output
OutPut

πŸ‘πŸ‘*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.

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/

Top comments (0)