How to use JSON in Ajax jQuery ?
Last Updated :
01 May, 2024
Using JSON in AJAX requests with jQuery is a fundamental aspect of web development. JSON or JavaScript Object Notation, offers a lightweight and structured format for data exchange between a server and a web application. jQuery simplifies this process further through its AJAX functionalities.
We will explore how to effectively use JSON in AJAX requests using jQuery.
Using the $.ajax() Method
In this approach, we are requesting the user information from the Node Server using the $.ajax() method. The server responds with user information that is in JSON format. The $.ajax() method offers versatility in making asynchronous HTTP requests. When the "Fetch User Data" button is clicked, an AJAX request is made to http://localhost:3000/users to fetch user data. If successful, the returned JSON data containing user names and ages is dynamically displayed on the webpage.
Steps to run the code:
npm i express
npm i cors
node server.js
Example: The below example shows how to use JSON in Ajax jQuery Using the $.ajax() Method.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity=
"sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<style>
h2 {
color: green;
}
button {
padding: 0.5rem 2rem;
border: 0;
border-radius: 0.5rem;
background-color: green;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<div>
<h2>GeeksforGeeks</h2>
<button id="fetchUserData">
Fetch User Data
</button>
<div id="userData"></div>
</div>
<script>
$(document).ready(function () {
$('#fetchUserData').click(function () {
$.ajax({
url: 'http://localhost:3000/users',
dataType: 'json',
success: function (data) {
displayUserData(data);
},
error: function () {
$('#userData').text('Error: Unable to fetch user data');
}
});
});
function displayUserData(data) {
var userDataHtml = '<ul>';
$.each(data, function (index, user) {
userDataHtml += '<li>Name: '
+ user.name + ', Age: '
+ user.age + '</li>';
});
userDataHtml += '</ul>';
$('#userData').html(userDataHtml);
}
});
</script>
</body>
</html>
JavaScript
/*server.js*/
const express = require("express");
const app = express();
const port = 3000;
const cors = require("cors");
app.use(cors());
const users = [
{ id: 1, name: "Alice", age: 25 },
{ id: 2, name: "Bob", age: 30 },
{ id: 3, name: "Charlie", age: 35 },
];
app.get("/users", (req, res) => {
res.json(users);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Output:
Fetchig user information user $.ajax() methodUsing the $.getJSON() Method
Example: In this example, we are requesting the user information from the Node Sever using the $.getJSON() method.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<style>
h2 {
color: green;
}
button {
padding: 0.5rem 2rem;
border: 0;
border-radius: 0.5rem;
background-color: green;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<div>
<h2>GeeksforGeeks</h2>
<button id="fetchUserData">
Fetch User Data
</button>
<div id="userData"></div>
</div>
<script>
$(document).ready(function () {
$('#fetchUserData').click(function () {
$.getJSON('http://localhost:3000/users',
function (data) {
displayUserDataJSON(data);
})
.fail(function () {
$('#userDataJSON')
.text('Error: Unable to fetch user data');
});
});
function displayUserDataJSON(data) {
var userDataJsonHtml = '<ul>';
$.each(data, function (index, user) {
userDataJsonHtml += '<li>Name: '
+ user.name + ', Age: '
+ user.age + '</li>';
});
userDataJsonHtml += '</ul>';
$('#userData').html(userDataJsonHtml);
}
});
</script>
</body>
</html>
JavaScript
/*server.js*/
const express = require("express");
const app = express();
const port = 3000;
const cors = require("cors");
app.use(cors());
const users = [
{ id: 1, name: "Alice", age: 25 },
{ id: 2, name: "Bob", age: 30 },
{ id: 3, name: "Charlie", age: 35 },
];
app.get("/users", (req, res) => {
res.json(users);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Output:
Fetching JSON using $.getJSON() method
Similar Reads
How to make a JSON call using jQuery ? Use the getJSON() function in jQuery to load JSON data. The getJSON() function uses a GET HTTP request to retrieve JSON-encoded data from the server. In this article, we will learn about the jQuery getJSON() function and its implementation through examples. Syntax: $(selector).getJSON(url, data, suc
3 min read
How to submit a form using ajax in jQuery ? Submitting a form using AJAX in jQuery allows sending form data to a server asynchronously without reloading the page. This method improves user experience by sending the data in the background and receiving a response without interrupting the user's interaction with the webpage.Syntax:$.ajax({type:
2 min read
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. In this article, we will see how to get JSON response in Ajax. Approach: To solve this problem,
4 min read
How to Update JSON Object Value Dynamically in jQuery? In jQuery, we can update JSON object values dynamically by manipulating the object directly or using utility functions. We will explore two approaches to update JSON object values dynamically in jQuery. Below are the approaches to update JSON object values dynamically in jQuery. Table of Content Usi
3 min read
What is the use of jQuery.ajax() method? AJAX is an important concept that must not be missed if you are learning front-end web development. It is an important aspect of the JavaScript programming language that allows the website to make requests to the server and exchange data without disturbing the page, that is without having it reload.
6 min read