The jQuery library offers a lot of features and functionalities, particularly in facilitating AJAX-related operations on web pages. With jQuery, we can execute server-side scripts, request new data from the server, and dynamically update our web pages without requiring a full reload.
One of the significant advantages of using jQuery for AJAX operations is its cross-browser compatibility. jQuery's AJAX functions work seamlessly across various web browsers, eliminating the need to write separate JavaScript code tailored for different browsers.
In this tutorial, we'll focus on fetching data from an API using an AJAX call and then displaying this data in an HTML table using jQuery.
We'll start by creating a simple HTML page containing a table, and then we'll use jQuery to fetch data from the API and populate the table with it.
We have to follow the following things:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1>How to display JSON data in HTML using ajax</h1>
<br />
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>ZipCode</th>
</tr>
</thead>
<tbody id="tblbody"></tbody>
</table>
</div>
</body>
</html>
For Our understanding purpose, let take an example, I have an API that returns the list of employees in the organization.
Now let’s say we want to bind that JSON response in the HTML table. Basically, we are going I want to Display JSON data in an HTML table using jQuery.
URL: http://samplerestapi.com/api/Metadata/GetEmployees
[ { "$id": "1", "Id": 1, "Name": "Pascale Cartrain", "Address": "Rua do Mercado, 12", "City": "Walla", "ZipCode": "243232" }, { "$id": "2", "Id": 2, "Name": "Liu Wong", "Address": "DaVinci", "City": "Paris", "ZipCode": "243232" }, { "$id": "3", "Id": 3, "Name": "Miguel", "Address": "Avda. Azteca", "City": "London", "ZipCode": "243232" }, { "$id": "4", "Id": 4, "Name": "Anabela", "Address": "ul. Filtrowa 68", "City": "New Delhi", "ZipCode": "243232" }, { "$id": "5", "Id": 5, "Name": "Mary Saveley", "Address": "Adenauerallee", "City": "Tokyo", "ZipCode": "243232" } ]
Here I’m calling the ajax function and displaying the JSON data, to a table which easy to read by the user.On success of Ajax call function BindDataWithJqueyEach
() javascript which loop through each object in JSON array,.
Below JavaScript/jQuery code is responsible for fetching data from an API endpoint and displaying it in an HTML table.
Below script demonstrates how to use jQuery to fetch data asynchronously from an API endpoint and dynamically populate an HTML table with the retrieved data.
<script type="text/javascript">
$(document).ready(function () {
GetBindData()
});
//Get all employees
function GetBindData() {
$.ajax({
url: 'http://samplerestapi.com/api/Metadata/GetEmployees',
method: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result)
{
//after successfully call bind data to Table
BindDataWithJqueyEach(result);
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
}
function BindDataToTable(data)
{
if (data != null && data) {
for (var i = 0; i < data.length; i++) {
var tablerow = "<tr>"
+ "<td>" + data[i].Id + "</td>"
+ "<td>" + data[i].Name + "</td>"
+ "<td>" + data[i].Address + "</td>"
+ "<td>" + data[i].City + "</td>"
+ "<td>" + data[i].ZipCode + "</td>"
+ "</tr>";
$("#tblbody").append(tablerow);
}
}
}
</script>
we are getting the data from server-side ajax response and we are trying to dynamically create table rows and add them to an existing HTML table. We can also use jQuery.each function if you don’t want to use the for loop.
This JavaScript function, BindDataWithJqueyEach, iterates over each element in the provided data array using jQuery's jQuery.each() method.
This function dynamically generates HTML table rows based on the data provided and appends them to the specified table body, effectively populating the table with the provided data.
See the below code.
function BindDataWithJqueyEach(data)
{
jQuery.each(data, function (i, val) {
var tablerow = "<tr>"
+ "<td>" + val.Id + "</td>"
+ "<td>" + val.Name + "</td>"
+ "<td>" + val.Address + "</td>"
+ "<td>" + val.City + "</td>"
+ "<td>" + val.ZipCode + "</td>"
+ "</tr>";
$("#tblbody").append(tablerow);
});
}
Full Code
function GetBindemployeesData() {
$.ajax({
url: 'http://samplerestapi.com/api/Metadata/GetEmployees',
method: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
//after successfully call bind data to Table
if (result && result.length > 0)
{
jQuery.each(result, function (i, val) {
var tablerow = "<tr>"
+ "<td>" + val.Id + "</td>"
+ "<td>" + val.Name + "</td>"
+ "<td>" + val.Address + "</td>"
+ "<td>" + val.City + "</td>"
+ "<td>" + val.ZipCode + "</td>"
+ "</tr>";
$("#tblbody").append(tablerow);
});
}
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
}
Output
* if you have a question please comment
If you want understand Deferred Object properly so that when we use these Deferred Objects and their Methods for AJAX Functionalities, then we can get a better understanding of how to internally Deferred Objects by AJAX Functionality.Promises and Deferred Objects
Many times during programming, such a situation arises that after one function is fully executed, the function that generates the result, a second function call is made to use that result.
And the result that generates after this second function is fully executed, that result has to be used in a third function and this process can continue even further.
That is, the third function cannot be executed until the second function is executed and generates the result and the second function cannot be executed until the first function is executed and generates the result. To fulfill this type of need, we usually have to create a function by nesting it up to several levels.
Deferred Object offers a solution to this problem. Deferred Objects provide the facility to write such codes, which are not executed exactly at the same time and place at which they are written, but they are executed in the future when they match any other specific situation. Let us try to understand the Processing of Deferred Objects with an example.
Suppose you apply to get a job in XYZ company and you are called for an interview by the company. Now XYZ Company is the function in which you have to perform.
The interview you will give in this company will be a result of that interview and the result will be that either you will get a job in this company or you will not get the job.
For both these types of results, you create a plan because for both types of results you have to make some plan and you cannot decide these plans after the interview is performed.
That is, before giving an interview, you have to decide that if you get a job then what will you do and if you do not get a job in this company, then what will you do.
For example, if you got a job, then you have to see the arrangement of living in the city where you will reside, till you want to do a job in that company. Whereas if you do not get a job, then in that case you will need to book a ticket to come back to your home town. Or some other similar work may have to be planned.