What is JSON & AJAX?

JSON & AJAX are the terms of javascript. JSON is a data format used for handling data with the server. We can store & receive data from the server easily. And AJAX is used for receiving data from the server on the browser without reloading or refreshing the browser.  Before starting to learn JSON & AJAX let learn a bit about object and array.

What is an Object?

First, see this code.

var myPet = {
    "name": "Meow",
    "species": "cat",
    "favFood": "milk"
}

Here myPet is an object. Now how to get the values of this object?

myPet.name

myPet.favFood

Here myPet.name will return the pet’s name “Meow” & myPet.fevFood will return “milk”.

What is an array?

Again see this code at first.

var myFavColors = ["blue", "green", "purple"];

Here myFavColors is an array. It’s writing pattern is with comma-separated value inside square brackets. Then how to access the value of this array?

myFavColors[1]

myFavColors[0]

myFavColors will return the second value “green”. Because array starts from 0. So when we need to get the first value we have to write myFavColors[0].

How to write an array of object?

On our example array paste our first object two or three times & separate them with comma. See below…

var myFavColors = [
 {
    "name": "Meow",
    "species": "cat",
    "favFood": "milk"
 },
 {
    "name": "Gheu",
    "species": "dog",
    "favFood": "milk"
  }
];

Here myFavColors is an array of object. You will be surprised that you have already learned JSON. JSON stores data as object notation. Its full name is JSON ‘= Javascript Object Notation. How to access this value? First, access your comma-separated array like this myFavColors[1] and then reach to the object like this myFavColors[1].favFood. This will return “milk”. Okay? ( Note: Starts from 0 ).

myFavColors[1].favFood

Before learning AJAX know a little about XMLHttpRequest.

What is XMLHttpRequest?

All modern browsers have a built-in tool( object ) to request data from the server. With this tool, we can send or receive data from the server without page reloading. Let’s see an example. Paste this snippet to your .js file. And view the console. I will explain it.

var yourReqst = new XMLHttpRequest();
yourReqst.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
yourReqst.onload = function(){
    console.log(yourReqst.responseText);
};
yourReqst.send();

On the first line, we have created a variable with a new instance of XMLHttpRequest. Then we have called JSON data with the open() method. The open() method accepts two parameters. The first for send or receive data. GET for receiving & POST for sending data. And the second is the URL from where you want to receive data. Here we have used GitHub data. You can see this from here.

The same data you will see on your console. On the third line, we have called a function with on loading the page. And on the last line, we have used the send() method the send the request.

Let’s see how to call specific data. To do this save ours to a variable. Then call the array on console.log().

var yourReqst = new XMLHttpRequest();
yourReqst.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
yourReqst.onload = function(){
    var yourData = yourReqst.responseText;
    console.log(yourData[0]);
};
yourReqst.send();

What do you see? Just a square bracket? Yes, you are right. Our “yourData” variable stores the data as an array. But inside the array, it stores the data just a plain text string. The first value of yourData is ‘ [ ‘ . So it’s showing this. But we don’t want this. We want the name. To get we need to tell the browser that we are calling a JSON data. How will we tell the browser it’s a JSON data? Just wrap the yourReqst.responseText with JSON.parse. See below…

var yourReqst = new XMLHttpRequest();
yourReqst.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
yourReqst.onload = function(){
    var yourData = JSON.parse(yourReqst.responseText);
    console.log(yourData[0]);
};
yourReqst.send();

View your console. See the name? Congratulations!!! You have learned the first bit of AJAX.

What AJAX stands for?

AJAX stands for Asynchronous JavaScript And XML. Here asynchronous means without reloading or refreshing. And XML is a data format something like JSON. But here we are not using XML. We are using JSON. That means AJAJS :). JSON is becoming a more popular data format than XML.

So you can say, then what about XMLHttpRequest? Yes, we will still use it. Because the browsers still use also for JSON data as a built-in tool.

Let’s see how to show the content on the front-end not on the console. Add a button with an id btn & add div with an animal-info. This div will contain the animal’s info.

<button id="btn">Fetch Info for 3 New Animals</button>

<div id="animal-info"></div>

And at last, add this snippet to your js file.

var containerDiv = document.getElementById("animal-info");
var btn = document.getElementById("btn");

btn.addEventListener("click", function(){
    var yourReqst = new XMLHttpRequest();
    yourReqst.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
    yourReqst.onload = function(){
        var yourData = JSON.parse(yourReqst.responseText);
        renderHTHL(yourData);
    };
    yourReqst.send();
})

function renderHTHL(any_name){
    var htmlString = "";
    for (i = 0; i < any_name.length; i++){
        htmlString += "<p>" + any_name[i].name + " is a " + any_name[i].species + ".</p>"   
    }
    containerDiv.insertAdjacentHTML('beforeend', htmlString);
}

Explanation: Here we added an event listener. When the button will be clicked the renderHTML function will be fired. This function holds a loop. The insertAdjacentHTML method will insert the values before the end of containerDiv.

Now click on the button. You will see the names and their respective species.

json & ajax tutorial

Thank you.

.

Leave a comment

Your email address will not be published. Required fields are marked *