0% found this document useful (0 votes)
11 views

How to get JSON response in Ajax

The document explains how to fetch JSON data using AJAX by creating an XMLHttpRequest object and populating an HTML table with country and capital information. It includes a sample JSON file, HTML structure for displaying data, and JavaScript code for handling the fetch operation. Additionally, it provides solutions for resolving CORS policy errors by setting up a local web server using Python or Node.js.

Uploaded by

raji7balag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

How to get JSON response in Ajax

The document explains how to fetch JSON data using AJAX by creating an XMLHttpRequest object and populating an HTML table with country and capital information. It includes a sample JSON file, HTML structure for displaying data, and JavaScript code for handling the fetch operation. Additionally, it provides solutions for resolving CORS policy errors by setting up a local web server using Python or Node.js.

Uploaded by

raji7balag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

How to get JSON response in Ajax ?

AJAX is a set of technologies that allows users to fetch data asynchronously without interfering with the existing page.

We can fetch various types of data using AJAX like JSON, XML, HTML, and text files.

Step 1: Let’s see the JSON content that we are having.

capitals.json
{

"countries_capitals":[

"country":"India",

"capital":"New Delhi"

},

"country":"Italy",

"capital":"Rome"

},

"country":"Germany",

"capital":"Berlin"

},

"country": "Egypt",

"capital":"Cairo"

},

"country": "Australia",

"capital":"Canberra"

Step 2: HTML file which contains a table named “Countries and their capitals”, and a “Fetch” button to click so that on clicking it we will be
able to populate the JSON data into the table.

<!DOCTYPE html>

<html lang="en" dir="ltr">

<head>

<meta charset="utf-8">
<title>Countries and Capitals</title>

<style>

body {

text-align: center;

h1 {

color: #44A075;

table {

border: 2px solid #44A075;

caption {

margin: 10px 0;

tr {

height: 30px;

th,

td {

border: 1px solid #44A075;

width: 100px;

.info {

display: flex;

justify-content: center;

button {

margin: 20px 0;

height: 40px;

width: 100px;

cursor: pointer;
}

</style>

</head>

<body>

<h1>Elysium Academy</h1>

<div class="info">

<table>

<caption>Countries and their capitals</caption>

<th>Countries</th>

<th>Capitals</th>

<tr>

<td class="countries"></td>

<td class="capitals"></td>

</tr>

<tr>

<td class="countries"></td>

<td class="capitals"></td>

</tr>

<tr>

<td class="countries"></td>

<td class="capitals"></td>

</tr>

<tr>

<td class="countries"></td>

<td class="capitals"></td>

</tr>

<tr>

<td class="countries"></td>

<td class="capitals"></td>

</tr>

</table>

</div>

<button id="fetchBtn" type="button" name="button">Fetch</button>

<script src="capitals.js" charset="utf-8"></script>

</body>

</html>
Step 3: Here is our JavaScript file which contains the code to get JSON response using AJAX.

First, we will grab all the HTML elements that are our “Fetch” button and “Countries and their capitals” table columns so that we can
populate it dynamically using DOM manipulation.

We will attach an Event Listener on our “Fetch” button.

Then, we will create an XMLHttpRequest object.

After creating the XMLHttpRequest object, we will call its open method to open the request, the open method takes three parameters, an
HTTP method(like GET, POST), URL of data that we want to fetch, and a boolean value(true means asynchronous request and false means
synchronous request).

Then, use the getResponseHeader method which returns the string containing the text of the specified header, here will use this method to
define which type of data we are fetching.

After this, we call the onload method which defines what to do after when the request completes successfully. Here in the onload method,
we are first parsing the response text and iterating through all countries and capitals columns one by one using forEach loop and
populating it with our parsed response text data.

At last, we will send a request to the server using the XMLHttpRequest object send method.

Capitals.js
const fetchBtn = document.getElementById("fetchBtn");

const countries = document.getElementsByClassName("countries");

const capitals = document.getElementsByClassName("capitals");

fetchBtn.addEventListener("click", buttonHandler);

// Defining buttonHandler function

function buttonHandler() {

// First create an XMLHttprequest object

const xhr = new XMLHttpRequest();

xhr.open("GET", "capitals.json", true);

xhr.getResponseHeader("Content-type", "application/json");

xhr.onload = function() {

const obj = JSON.parse(this.responseText);

Array.from(countries).forEach((country, index) => {

country.innerText = obj.countries_capitals[index].country;

});

Array.from(capitals).forEach((capital, index) => {

capital.innerText = obj.countries_capitals[index].capital;

});

xhr.send();

}
How To Fix The Access To Script At …… From Origin ‘null’ Has Been Blocked By CORS Policy Error.

To fix this error is also easy, what you need to do is to create a local web server, and then upload the Html and JS file to the webserver.

Then you can browse the Html file in the web browser with the HTTP or HTTPS protocol, and then it will also load the external JS file using
the HTTP or HTTPS protocol also.

If you use python3, you can follow the below steps to access the Html file from a local webserver.

Open a terminal and go to the Html file saved directory, and run the command python -m http.server as below.

D:\Work\dev2qa.com-example-code\PythonExampleProject\html\canvas\snowflake-404-page>python -m http.server

Serving HTTP on :: port 8000 (http://[::]:8000/) ...

The command python -m http.server will start a local webserver and listen on the port with the number 8000.

And the Html file is just saved in the root directory of the local webserver, then you can access it on the web browser with the URL
http://localhost:8000/test.html.

Now you will find the error will be fixed.

Node.js

Alternatively, if you demand a more responsive setup and already use nodejs...

Install http-server by typing npm install -g http-server

Change into your working directory, where yoursome.html lives

Start your http server by issuing http-server -c-1

This spins up a Node.js httpd which serves the files in your directory as static files accessible from http://localhost:8080

You might also like