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
- croppie plug-in does not work using ajax /innerHtml content
- Trigger a pop up modal div after 1 minute
- Handling AJAX errors in React.componentDidMount
- Javascript: Select Textarea, Type then Enter
- Trying to change opacity in css onclick
- How can I detect when an element scrolls into the viewport using in-view.js
- jquery datatable traverse TR to see id exists before add
- redirect after few second on click jquery
- Simple modal JSON Jquery
- color picker doesn't show in my code
- Datepicker does not work properly in modal where html is returned using jQuery .load()
- How to hide a parent element when click to iframe
- MVC: How to use accomplish "partial validation" technique, displaying just a warning and validating the model?
- I have an ajax call firing twice (jQuery) and have tried the solutions found here and nothing has worked
- Apply custom validation in select2
- Part 2. Select and Change elements with a certain background color
- Bootstrap tags:Type ahead is not working
- Shoping cart realization Javascript. TypeError: Cannot set property 'id' of undefined
- jquery remove content inside a tag 'x' but before tag 'y'
- Owl carousel jumpt to specific index after ajax call
- Script70 Error in Frame-context
- Can't get mask to work with Save/Edit on input
- How to retry ajax on fail in react js?
- JQuery autocomplete disable some results
- pass URL of actual page in the input field of other page with jquery/js
- jQuery-Tabledit throws MethodNotAllowedHttpException
- Hover over the para should display the same content in jquery
- jQuery autoescaping Django templatetags
- not getting radio button values in jquery ajaxform
- Amcharts - sortable div moves when chart scroll bar is scrolled
- How to write error message on sides of textbox, without using any other tag in JQuery?
- getting attr id undefined on click button jquery
- Jquery Slider - get every numeric value of the slider? not only on mouseout?
- Radio button not checked the second time
- Background Image Cycle - z index with smooth fade or transition
- Move a DOM element Using jQuery
- Script works in html but not in javascript file
- Why are changes to classes ignored after dom changes?
- timing with keyup, keydown, and keypress
- Text hides underneath image
- Unable to animate Font Awesome Icon using Vivus
- How can I manipulate the DOM with the web audio API/javascript?
- Jquery css left change of image depending on div width
- Rails, JSON api returning prices of an item list
- Jquery delayed RSS feed replaces all html in the page
- CodeIgniter validation with javascript / jquery
- Adjusting bootstrap dropdown with textbox to content width
- Javascript NoGray Calendar find next available date after chosen blocked dates if today is blocked
- File_put_contents not overwriting on img /Firefox
- Trying to call a jquery function with no event
- Bootstrap 4 JS Throwing Error on SO Embed Snippet Fiddle
- Invoke Angular2 Component function from VisJS Event
- MaterializeCss : How to enable different checkboxes with JQuery in multiple select?
- best practice: should i unbind on custom widget
- Return the first option of select
- Can't Open A Div On Click — Trying to Change it's height from 0 to it's actual size
- jQuery dropdown menu not working second time
- Having Issues with isotope filtering in fancybox
- Refresh Div Content (local .html only)
- How to move focus on next field when enter is pressed? I tried many approaches but nothing is working
- How to prevent click event if click starts on child div and ends on parent (Chrome bug)
- How to destroy / cleanup jsviews?
- jQuery in .net validate dropdownlist, fadein and fadeout panels
- Bootstrap-multiselect show hide div elements
- Knockout protected observable
- How to edit the index page of wordpress theme?
- AJAX request for REST service in Jquery, Getting response when parameters are sent through URL but not through data object
- jquery move element before closest
- jquery show hide div based on select value dynamically
- My $(document).ready(function() work in local but not on Cloud9
- Finding all elements bound to a function in jQuery?
- Need help keeping text on 3 lines regardless of length
- jQuery: Two progress bars inside one div
- How to assign a Backbone button not belonging to a view, to an action?
- Stop scrolling at some point
- this scope maintained when using jQuery
- Drag and Drop between 2 tables using Jquery sortable with rowspan and colspan
- using google apis for jquery ui
- jquery not working in IE, Chrome, works in FF
- Select list item parent without children in nested lists in jQuery
- Direct linking to tabulous tabs
- jQuery Post Not Working in OS X Chrome
- Multiple select val() returning null
- Add Time Scaling to linechart (Chart.js)
- java script checks two input values only by digit
- Wait for template own Event to change Session for own Helper
- Can't read xml data into a web page
- Auto refreshing grid and being able to update part of data within the grid
- Re-arrange Text Input fields based on Number entered by user
- Form validation blocking the entire page
- javascript flot threshold with positive and negative limits (+/-)
- make footer grow with jquery/css
- jQuery text() checking not working properly with Twitter Bootstrap 3
- Ajax DELETE request seems to remove first item on the list only
- jQuery .find() does not work on async elements loaded via Angular
- Cleaning up mouseenter by calling a function?
- Wordpress: (When Fixing Overlapping Masonry Issue) Encountered unexpected end of file in functions.php
- Not displaying after quote mark
- Change text color of inner html value with jQuery
- customize autocomplete field in google map api
- Ajax DELETE redirects even if prevented
- API development, Bootstrap and jQuery. Good idea to inject them all in user's code?
- show column filters with autocomplete in jquery datatable server data
- How to add autocomplete to dynamically added input fields? The autocomplete does not work on the dynamically added input fields
- Jquery Validation Plugin - Select Box Problems
- call a function after all fadeOut
- Jquery class attribute navigation
- Turbolinks not working (page loads twice)
- jquery .post not working
- How to get input from multiple text boxes
- Carousel Slider - Link does not work on another subpage
- Sending variable to another php file
- PHP unable fetch UTF8 from database
- How can I write a Protractor test for a listed tab element where it checks if it's active or not?
- AutoNumeric change value
- Django: load template after AJAX request
- How can I hide the text box in jquery for initial loading?
- Direct url link to Modal popup (SimpleModal)
- <object> for PDF is blocking drop-down menu
- Keeping textboxes hidden and shown in synch
- How to capture checkbox input
- How do I remove variable randomly using jquery?
- jQuery/JavaScript Execution Order
- Showing Result with Ajax
- Disable hashchange until scrollling has stopped
- Issue with slideUp/slideDown JS
- Jquery datatable makeEditable update without pressing enter
- How to use events and event handlers inside a jquery plugin?
- How to use code for MATH MML in Jquery in XML Parser
- How to change default search engine with javascript on chrome
- Set Tuple of List to ViewData Mvc C#
- Displaying sub-categories next to the main categories using CSS after PHP generation
- Changing a CheckBox BackColor with no PostBacklike AJAX
- ajax HTML content not rendering in bootstrap pop
- Jquery caching data-* attributes
- Graphical Countdown in Jquery/Javascript/ASP.NET
- jquery get not working after submit
- how to fire client side and MVC validations together?
- Basic jQuery with Rails
- Lost on AJAX to .ASP file
- Show/hide div with JQuery
- jquery randomly animate div (zoom in and out)
- Three select elements updates depending on each other
- Using info from GET request in jQuery to display transformed result through Flask
- Find match in id name and assign to to title tag
- Javascript JQuery Listview Refresh Error Msg - Uncaught TypeError: undefined is not a function
- jQuery .bind method not activating the second time?
- Modal not launching jquery
- jquery ui datepicker select only current and previous month
- Datatable not working when another AJAX is used