The jQuery Library provides us with all kinds of features and functionalities to get AJAX-related features on our web pages. That is, jQuery provides us with such functions, using which we can run any server-side script in our web page or request new data from the server without reloading our web page and send the incoming new data to our web.
Also, the functions that jQuery provides us related to AJAX, work in all web browsers due to being completely cross-browser compatible. Therefore, we do not need to write different JavaScript codes for different web browsers using different methods.
Today we will learn how to fetch data from API using ajax call and display it in an HTML table using jquery.
We will create a simple HTML page with a table that displays the data using jquery.
We have to follow the following things:
- First, we have to create an Html page and a table in it.
- Add Reference of Bootstrap of CSS and Style
- Write JavaScript Code for Getting Json using Ajax call.
- Final Step Display json data from jQuery.ajax in HTML using loop
Step 1: Create Html page and table
<!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>
Step 3: Display JSON data from URL using Ajax
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://restapi.adequateshop.com/api/Metadata/GetEmployees
Json Response:
[ { "$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" } ]
Display JSON response from Ajax as HTML or table
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,.
<script type="text/javascript">
$(document).ready(function () {
GetBindData()
});
//Get all employees
function GetBindData() {
$.ajax({
url: 'http://restapi.adequateshop.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>
Method-2 Using jQuery.each function bind data in the table
Using jQuery to build table rows from AJAX response
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. 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://restapi.adequateshop.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.
The post [Best Way]-How to display JSON data in HTML using Ajax appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- Javascript to jquery issue
- Calling a php function by an jquery ajax request and updating a div by the return object
- A short way of cheking multiple blank text fields jQuery
- Troubleshoot jquery error with dropdown menu
- How to generate Index of user given value in textbox?
- JQuery - Deselect/ Click Off an attribute
- JQuery need to click twice to launch script
- JQuery/CSS: Animate static position
- Load when the browser is open
- Manipulate ajax response
- start date is less than end date?
- Jquery UI sortable event params not work as documented
- Not able to count characters using jQuery
- How to get inner element using parent object without using parent and children jquery function
- Smooth scroll not working after zoom css using for body
- Why in javascript would an self-called anonymous function surround a jQuery onReady callback?
- jquery <li> on click navigate to url and add class after
- Bootstrap hamburger menu not expanding
- boolean variable in jquery
- Handling knockout text that contains string and html
- How to write the correct AJAX URL in Laravel
- Issue with jQuery fade in
- Select menu not changing .css
- How to remove object from a array?
- Refresh current page at the end of PHP Ajax call
- How to add something in html string
- Centering the toggle button in Bootstrap 3
- Iterate over table updating currency for each cell javascript / Jquery
- How to wait until jquery animation is finished using the onbeforeunload event?
- link_to with remote => true not functioning as expected
- Control number showing max value
- if/else statement inside .ajax
- Jquery - remove class only when item is active
- Creating a dynamic popup for Disqus comments for different threads
- Twitter bootstrap datepicker
- How do I make a scroll to top button appear when a pre-determined part of the page appears?
- How can I use jquery to select elements from array and add class?
- Please help me to understand jQuery's new .on method
- Cors error when sending a PUT request with ajax API
- jQuery setInterval not looping
- Select multiple div IDs using a single css selector
- jQuery Setup and issues
- Form when submitted to display a result (Firstname) on the thank you page
- Validate date on keypress not working
- Mouse hover on image parts show hints
- Each link should open a div
- HTML reset button in combination with text field values set with jQuery
- jQuery Remove LI elements inside UL
- take an attribute from a list of objects
- Jump to next slide onClick
- Where to remember values needed for onSelect
- JQuery Error in my .PHP file
- javascript : Identify the form in the loop after submission?
- how to compare listbox values and table values in javascript?
- jQuery append: can't get the quotes right
- Two submit buttons in one form with different actions
- jquery manipulate html
- Get values of selected checkboxes and their associated textareas in Javascript
- Android submit https login form which uses jquery
- jQuery #div scroll
- Angular {{$index}} integration with jquery plugin
- dynamically update height of browser window
- shouldn't keep textarea data?
- Appending options to select element doesn't work - MaterializeCSS
- Why is this ajax form not working?
- jquery: keep only single selected div
- How To Add Class To Parent Div which contains image of certain size?
- Validate is not a function
- How do I check if an element exists inside an iframe?
- Add an event on the radio button
- Jquery not work after content is loaded with AJAX
- not :contains isn't working
- Jquery Datatables plugin CSS defaults not being applied. Pagination and search appear on the left side of the table. and without styles
- lightbox_me not working on click event
- jquery filter xml data by attribute value
- jQuery combine toggle with click
- selected rows of gridview not changing, instead all rows are changing
- JQuery On not being hit when click on link
- Multiple column filtering in a single dropdown in DataTables
- jQuery Organization of document.ready logic
- Web-based Circular Interface Frontend - No Graphics!
- Json array creation using javascript / jquery
- Jquery - Getting data from database when dialog window opens
- Add a price with the chosen quantity - JavaScript
- Is it safe to wrap a function inside jQuery.removeClass()?
- .html() not show result in jquery
- JavaScript - Read XML Document
- What is variable f supposed to contain in this example?
- Neo4j: How to have '|' as delimeter when export data in csv?
- Load different template file for different browsers
- Divs with the content of modal dialogs are visible before the DOM loads
- Start action after second click at element class with jQuery
- find last html element with jquery for special attribute
- swipe carousel and cube display in jquery mobile
- jQuery getJSON syntax error
- Get HTML Divs From PouchDB
- how to scroll 2 divs at the same time with iScroll
- display data dynamically in form
- jQuery UL Tabs duplicate navigation?
- Javascript replace content in <li> tag
- jQuery Selector (children, eq, and innerhtml)
- ul li dropdown menu won't show li items after clicking any li item
- supersized stop resizing
- jQuery Cycle Plugin stop on first slide after first loop
- JQplot barchart example not displaying
- Checkbox checked add class
- Issue with parsing JSON
- How to reload page when an ajax request returns FormsAuthentication.RedirectToLoginPage?
- Jquery form submit behavior not understandable
- Why Javascript Ajax call fails over SSL on IOS devices except IOS 5.
- Key-Value Pair Json transformation and conversion into a class in Javascript / Jquery
- jQuery ajax request, PHP returns false but no error
- Checkbox unchecked state
- DataTables ajax don't work
- get the value of span inside a div jquery
- Toggle image(flag's) in language panel
- Double and triple button is shown (DOMNodeInserted)
- after decimal allow 4 digit and before decimal 2 using javascript
- Difference between prop and trigger
- How to split a string on the spaces in Javascript & HTML?
- uncaught referenceerror: 'yyyyyy' is not defined
- JQuery : Count children that is checked in a <li> tag
- Change content of a div which has a non unique class
- Jquery: Compare input values to array objects and see if they match exactly
- create jquery function to run from html that's created from within another function
- Unable to output multiplication of values from textboxes (possibly NAN) - Backbone.js
- JQuery search on page load
- onclick="location.href='<?php the_permalink() ?>';" open in new window
- AJAX form not displaying succes or error message
- Attach fancybox/lightbox/idontknowbox function on an element
- jQuery Toggle Divs next to each other with display:inline-block
- Take a TD, and insert it after the second TD in the parent TR
- Jquery Add a delay in P text swap
- How to find visible order of two elements?
- why does my 'click' addEventListener getting called on pageload
- Hide a div's span when a different div contains specific text with jquery
- Triggering an event when a css value changes
- JQ Tree not rendering properly
- find value of enabled textarea by class
- Click handler is not getting called on nested span element
- Hover to show/hide div
- AJAX based page needs repetitive javascript actions
- How can I store elements to pass to .not()?
- Show an executed script result in a html div tag
- jquery issue: how to break and reset setinterval?
- javascript click event :click once trigger twice callback function?
- Calling function from iframe not loading
- Jquery Checked Selector
- JQuery add class and remove class div animation
- Playframework 2.1.2 how to prevent scala function calls on template load?