Jquery datatable plugin not loading - html

Datatable was not working. Even console has no errors regarding datatables. Once the page gets loaded, the datatable plugin was not even loading. I tried with cdn links too, still the plugin was not working with my script.
Below is my sample code:
$('#newtable').dataTable( {"pagingType": "full_numbers"} );
<table class="table table-bordered table-hover" id="broker" cellspacing="0">
<thead>
<tr><th class="info">Broker</th>
<th class="info">Address</th>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tbody>
</table>
Scripts and css added:
<script src="-/scripts/jquery.dataTables.min.js"></script>
<link href="-/styles/datatables.css" rel="stylesheet">
<link href="-/styles/datatables.responsive.css" rel="stylesheet">
<script src="-/scripts/datatables.responsive.js"></script>
Here is the exact script I have used to populate the table and map for a page:
setTimeout(function() {
$(document).ready(function() {
// Search button clicked
$('#btnSearch').click(function(e) {
e.preventDefault();
$('#searchUserLongitude').val("");
$('#searchUserLatitude').val("");
// Do an AREA search
getBrokerSearchList('AREA');
});
// Hide certain text/functions if geo-location is not available
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(function(position) {
$("#findAdvisor").removeClass("hide");
$("#findAdvisorOr").removeClass("hide");
$("#findAdvisorText").removeClass("hide");
$('#searchGpsAvailable').val("Y");
}, function() {
//do nothing.
});
}
});
}, 1000);
function openInfo(agentCode, lat, lng) {
var googleMap = this.APP.instances.googleMap;
googleMap.openInfo(agentCode, lat, lng);
window.location = '#map';
}
function glSuccess(lat, lon) {
$('#searchUserLongitude').val(lon);
$('#searchUserLatitude').val(lat);
$('#searchTownStreet').val("");
$('#searchPostCode').val("");
$('#searchPostCode').trigger('render.customSelect'); // Update the dropdown
// Do a GPS search
getBrokerSearchList('GPS');
}
/*
* Function to call if the browser doesn't support geoLocation or the
* user declines to send their position
*/
function glFail() {
alert('Sorry. Either your browser does not support geoLocation, or you refused the request.');
}
// Get the fund prices
function getBrokerSearchList(typeOfSearchRequested) {
$("#advisorFinder").addClass("hidden");
$("#finalSection").addClass("invisible");
$("#messagePleaseWait").removeClass("hidden");
$("#messageError").addClass("hidden");
$("#messageNotFound").addClass("hidden");
$("#messageErrorService").addClass("hidden");
var searchTownStreet = $("#searchTownStreet").val();
var searchPostCode = $("#searchPostCode").val();
var searchUserLatitude = $("#searchUserLatitude").val();
var searchUserLongitude = $("#searchUserLongitude").val();
var searchGpsAvailable = $("#searchGpsAvailable").val();
// AJAX call to get advisor search data (JSON), and update the page based on it
$.ajax({
type: 'POST',
url: '/services/findAdvisors?searchTypeOfSearchRequested=' + encodeURIComponent(typeOfSearchRequested) + '&searchTownStreet=' + encodeURIComponent(searchTownStreet) + '&searchPostCode=' + encodeURIComponent(searchPostCode) + '&searchUserLatitude=' + encodeURIComponent(searchUserLatitude) + '&searchUserLongitude=' + encodeURIComponent(searchUserLongitude) + '&searchGpsAvailable=' + encodeURIComponent(searchGpsAvailable),
dataType: "json", //to parse string into JSON object,
success: function(data) {
if (data) {
if (data.errors) {
// We got data back from the service, but there are errors
// Show/hide the appropriate sections
$("#advisorFinder").removeClass("hidden");
$("#messagePleaseWait").addClass("hidden");
var htmlErrors = "<div class='alert alert-danger custom-alert'>";
var displayErrors = false;
// Loop over all of the errors returned and attempt to deal with each one individually
for (var prop in data.errors) {
htmlErrors = htmlErrors + "<p>" + data.errors[prop].toString() + "</p>";
displayErrors = true;
}
htmlErrors = htmlErrors + "</div>";
if (displayErrors) {
$("#messageErrorService").empty().append(htmlErrors);
$("#messageErrorService").removeClass("hidden");
}
// Tidy up the boxes
$(window).trigger('resize');
} else {
// Update the search results
var lenAdvisorList = data.findAdvisorResultList.length;
var htmlAdvisorList = "";
var protocol = "";
if (lenAdvisorList > 0) {
// We have results
// Build the HTML
htmlAdvisorList += "<div class='box-simple'>";
htmlAdvisorList += "<div class='content' style='padding:5px'>";
htmlAdvisorList += "<div class='table-wrapper' style='margin-top: 15px;'>";
htmlAdvisorList += "<table cellspacing='0' class='table table-bordered table-hover datatables' id='broker'>";
htmlAdvisorList += "";
// Add the table header
htmlAdvisorList += "<thead>";
htmlAdvisorList += "<tr>";
htmlAdvisorList += "<th class='info'>Broker</th>";
htmlAdvisorList += "<th class='info'>Address</th>";
htmlAdvisorList += "<th class='info'>Phone</th>";
htmlAdvisorList += "<th class='info'></th>";
htmlAdvisorList += "</tr>";
htmlAdvisorList += "</thead>";
// Add the table rows
for (var i = 0; i < lenAdvisorList; i++) {
if (data.findAdvisorResultList[i].agentNumber) {
htmlAdvisorList += "<tr data-unqcode=" + data.findAdvisorResultList[i].agentNumber + " data-address=" + data.findAdvisorResultList[i].address + " data-location=" + data.findAdvisorResultList[i].brokerLatitude + "," + data.findAdvisorResultList[i].brokerLongitude + ">";
htmlAdvisorList += "<td>" + data.findAdvisorResultList[i].agency + "</td>";
htmlAdvisorList += "<td>" + data.findAdvisorResultList[i].address + "</td>";
htmlAdvisorList += "<td><a href='tel:" + data.findAdvisorResultList[i].workphone + "'>" + data.findAdvisorResultList[i].workphone + "</a></td>";
htmlAdvisorList += "<td width='32'>";
htmlAdvisorList += "<a id='" + data.findAdvisorResultList[i].agentNumber + "' href='#'><img width='32' height='32' src='-/assets/elements/icon_map.png'></a>";
htmlAdvisorList += "<div class='hidden'>";
htmlAdvisorList += "<div class='info-window'>";
htmlAdvisorList += "<p><strong>" + data.findAdvisorResultList[i].agency + "</strong></p>";
htmlAdvisorList += "<p>Address: <strong>" + data.findAdvisorResultList[i].address + "</strong></p>";
htmlAdvisorList += "<p>Phone: <strong>" + data.findAdvisorResultList[i].workphone + "</strong></p>";
htmlAdvisorList += "<p>Email: <strong>" + data.findAdvisorResultList[i].email + "</strong></p>";
if (data.findAdvisorResultList[i].website != '' && data.findAdvisorResultList[i].website.substring(0, 4) != 'http') {
protocol = "http://";
} else {
protocol = "";
}
htmlAdvisorList += "<p><strong>Website:</strong> <a target='_blank' href='" + protocol + data.findAdvisorResultList[i].website + "'>" + data.findAdvisorResultList[i].website + "</a><br/></p>";
htmlAdvisorList += "</div>";
htmlAdvisorList += "</div>";
htmlAdvisorList += "</td>";
htmlAdvisorList += "</tr>";
}
}
// Clear the existing HTML for the results list
$('#resultsList').empty();
// Show the new HTML + other page updates
if (htmlAdvisorList != "") {
$("#resultsList").append(htmlAdvisorList);
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageNotFound").addClass("hidden");
// Initialise the map
// Will read the data from the table and populate the map
// Must happen before the datatables update
APP.instances.googleMap.init();
// Initialse the datatables
$('#broker').dataTable({
"pagingType": "full_numbers"
});
}
// Tidy up the boxes
$(window).trigger('resize');
} else {
// We don't have results
// Clear the existing HTML for the results list
$('#resultsList').empty();
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageNotFound").removeClass("hidden");
// Initialise the map
APP.instances.googleMap.init();
// Tidy up the boxes
$(window).trigger('resize');
}
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
// We got an error during the AJAX call
// Clear the existing HTML for the results list
$('#resultsList').empty();
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageError").removeClass("hidden");
$("#messageNotFound").addClass("hidden");
// Initialise the map
APP.instances.googleMap.init();
// Tidy up the boxes
$(window).trigger('resize');
}
});
}

The reason is because you're using the wrong table ID. You declared the table with "broker":
<table class="table table-bordered table-hover" id="broker" cellspacing="0">
But then instantiate the DataTable with "newtable":
$('#newtable').dataTable( {"pagingType": "full_numbers"} );
The solution is to change your line to be:
$('#broker').dataTable( {"pagingType": "full_numbers"} );

Any time you're having issues with a library not working as expected, it's usually a good idea to double check the links you're using to request the library. You'll also want to make sure your table markup is correct as well. Lastly, the table id in your html needs to be the same as the selector you use to initialize the table features in your jQuery.
The solution below resolves these issues and works. Hope this helps!
$(document).ready(function() {
$('#broker').DataTable({
"pagingType": "full_numbers"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="broker" class="display table table-bordered table-hover" style="width:100%" cellspacing="0">
<thead>
<tr>
<th>Broker</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Broker</th>
<th>Address</th>
</tr>
</tfoot>
</table>

Related

Is there a good package/library to add Pagination/Sorting/Searching to my table? ASP.NET Core

I am new to web development in ASP.NET Core. I have a table with information, I would like to add pagination/sorting/searching to the table. Is there an easy way to add this using some sort of library/package? Thanks
I need pagination, sorting, and searching for my ASP.NET Core table.
I would like to add pagination/sorting/searching to the table. Is
there an easy way to add this using some sort of library/package?
Well, considering all the requirement you can go for jquery data table regardless of simplicity, quick implementation and free subscription. Importantly, its light weight and easy to use.
Here is the compplete example how you can implement that:
Controller:
[HttpGet]
public IActionResult ConAction()
{
var controlleractionlist = _context.Controller.ToList();
return Json(controlleractionlist);
}
Note: I am returning a simple list to demonstrate you , sorting, searching and paging functionality.
View:
<table id="userTable_info" >
<thead>
<tr>
<th>action </th>
<th>controller </th>
<th>returnType</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
//Button Click Functions
function DetailsFunc(data) {
alert("User Id:" + data + " Details!");
}
function EditFunc(data) {
alert("User Id:" + data + " will be Edited!");
}
function DeleteFunc(data) {
alert("User Id:" + data + " will be deleted!");
}
//On Load
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://localhost:5094/Home/ConAction',
dataType: "json",
contentType: "application/json",
success: function (response) {
console.log(response);
var id = 0;
$.each(response, function (index, value) {
id++;
console.log(id);
var tr = "<tr>";
tr += "<td>" + value.action + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.returnType + "</td>";
tr += "<td>" + "<input type='button' id='" + id + "' class='btn btn-info' onclick='DetailsFunc(" + value.id + ")' value='Details'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
}
});
});
</script>
}
Output:
You could refer to official document for more details.

How to sort data according to date using jquery

l have data JSON coming from URL and l displayed those data in a table.
As you see l have different time dates. l want to add a new element above '12:15 am' to display the full date to make the user know that is a new day as the image below.
Code :
function airport() {
var airport_data = ""
$.ajax('my_airport.json', {
type: 'GET',
dataType: 'json',
timeout: 5000,
cache: false,
}).done(function (data, textStatus, jqXHR) {
data.forEach(element => {
if (element.flight.status.generic.status.text == 'scheduled') {
airport_data += '<tr>';
airport_data += '<td><p>' + element.flight.airline.name + '</p></td>';
airport_data += '<td><p>' + element.flight.identification.number.default + '</p></td>';
if (element.flight.aircraft == null) {
airport_data += '<td><p>N/A</p></td>';
} else {
airport_data += '<td><p>' + element.flight.aircraft.model.code + '</p></td>';
}
airport_data += '<td><p>' + element.flight.airport.origin.position.region.city + '</p></td>';
/// time is here
airport_data += '<td><p>' + moment.unix(element.flight.time.scheduled.arrival).format("h:mm a") + '</p></td>';
airport_data += '<td><p>' + element.flight.status.generic.status.text + '</p></td>';
if (!element.flight.time.scheduled.arrival) airport_data += "<tr><td><p>N/A</p></td></tr>";
}
document.getElementById("data").innerHTML = airport_data
var rows = $("#data");
rows.hide();
$('.row-data:last-child').after(rows);
rows.fadeIn(500);
});
})
}
html :
<div class="table-responsive">
<table class="table table-condensed text-center table-hover"">
<thead>
<tr>
<th>AIRLINES</th>
<th>CALLSIGN</th>
<th>TYPE</th>
<th>FROM</th>
<th>TIME</th>
<th>STATUS</th>
</tr>
</thead>
<tbody id="data" class="data">
</tbody>
</table>
</div>
If the rows comes already sorted you just have to insert the additional rows every time the date is going to change. Do it this way:
before entering the forEach initialize a variable called prevDate with an empty string;
inside the foreach, before appending the flight row, format the arrival as YYYYMMDD and assign it to a variable called currentDate;
compare currentDate with prevDate, if they differ then add the date header;
assign currentDate to prevDate.
That's all.
EDIT
First, let me say you have a syntax error in your html, you have closed the double quote 2 times on the table class.
Second, your js code is iterating over the root of the json returned by the ajax call, but the json you have added in the comment has a more nested structure, the array is located down to "data.result.response.airport.pluginData.schedule.arrivals.data".
So, after resambling the above, your code should become like this:
<html>
<head>
<script src="jquery-2.x-git.min.js"></script>
<script src="moment.js"></script>
<script>
$(airport);
function airport() {
var airport_data = ""
$.ajax('my_airport.json', {
type: 'GET',
dataType: 'json',
timeout: 5000,
cache: false,
}).done(function (data, textStatus, jqXHR) {
var prevDate = '';
data.result.response.airport.pluginData.schedule.arrivals.data.forEach(element => {
var curDate = moment.unix(element.flight.time.scheduled.arrival).format("YYYYMMDD");
if (curDate != prevDate) {
airport_data += '<tr><td colspan="5">ARRIVALS - '+
moment.unix(element.flight.time.scheduled.arrival).format("dddd, MMM D")+
'</td></tr>';
prevDate = curDate;
}
if (element.flight.status.generic.status.text == 'scheduled') {
airport_data += '<tr>';
airport_data += '<td><p>' + element.flight.airline.name + '</p></td>';
airport_data += '<td><p>' + element.flight.identification.number.default + '</p></td>';
if (element.flight.aircraft == null) {
airport_data += '<td><p>N/A</p></td>';
} else {
airport_data += '<td><p>' + element.flight.aircraft.model.code + '</p></td>';
}
airport_data += '<td><p>' + element.flight.airport.origin.position.region.city + '</p></td>';
/// time is here
airport_data += '<td><p>' + moment.unix(element.flight.time.scheduled.arrival).format("h:mm a") + '</p></td>';
airport_data += '<td><p>' + element.flight.status.generic.status.text + '</p></td>';
if (!element.flight.time.scheduled.arrival) airport_data += "<tr><td><p>N/A</p></td></tr>";
}
document.getElementById("data").innerHTML = airport_data
var rows = $("#data");
rows.hide();
$('.row-data:last-child').after(rows);
rows.fadeIn(500);
});
})
}
</script>
<head>
<body>
<div class="table-responsive">
<table class="table table-condensed text-center table-hover">
<thead>
<tr>
<th>AIRLINES</th>
<th>CALLSIGN</th>
<th>TYPE</th>
<th>FROM</th>
<th>TIME</th>
<th>STATUS</th>
</tr>
</thead>
<tbody id="data" class="data">
</tbody>
</table>
</div>
</body>
</html>
The rest is a matter of styling.

How to add pagination to JSON table in HTML using JQuery?

HTML
This code retrieves the JSON data from the external source and displays it inside the table, it has total 50 rows of data, now I need to add pagination to the page that shows 10 data rows per page without losing the current functions[Drop-down function, Console log etc..], any help will be apprecieated, thank you!
NOTE: external JSON data doesn't work on live previews, please open the index page directly on browser.
<body>
<div class="container">
<select class="more"></select>
<table class="table table-hover pagination-page" id="table" style="width:100%">
<tbody>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Username</th>
<th>E-mail</th>
<th>Age</th>
<th>gender</th>
<th>maritial status</th>
</tr>
</tbody>
</table>
<span id="PreValue" class="pagination-page">Previous</span> |
<span id="nextValue" class="pagination-page">next</span>
</div>
</body>
</html>
SCRIPT
$(document).ready(function () {
fetch('http://fakeapi.jsonparseronline.com/users')
.then(res => res.json())
.then((out) => {
console.log('Output: ', out);
}).catch(err => console.error(err));
var users= [];
$.getJSON('http://fakeapi.jsonparseronline.com/users', function(data) {
users = data;
buildSelect();
listUsers(1, 10);
});
function buildSelect() {
var sdata = "";
$.each(users, function (key, value) {
if (key % 10 === 0) {
sdata += `<option data-start-index="${key + 1}" data-end-index="${key + 10}">${key + 1} - ${key + 10}</option>`;
}
});
$(".more").html(sdata);
}
function listUsers(start, end) {
var udata = "";
$.each(users.slice(start-1, end), function (key, value) {
udata += "<tr>" +
"<td>" + value.id + "</td>" +
"<td>" + value.firstName + "</td>" +
"<td>" + value.lastName + "</td>" +
"<td>" + value.username + "</td>" +
"<td>" + value.email + "</td>" +
"<td>" + value.age + "</td>" +
"<td>" + value.gender + "</td>" +
"<td>" + value.phone + "</td>" +
"</tr>";
});
$('#table').html(udata);
$("#table tbody tr").click(function() {
var $row = $(this).closest("tr");
var $text = $row.find("td").text();
alert($text);
});
}
buildSelect();
listUsers(1, 10);
$(document).on("change",".more",function() {
startIndex = $(":selected", this).attr("data-start-index");
endIndex = $(":selected", this).attr("data-end-index");
listUsers(startIndex, endIndex);
});

Populate HTML table with JSON data

We would be grateful for some guidance, [we are early into coding] and have looked at lots of examples but can cannot get our JSON to import into the table.
At that moment we have the table data in-line however a correctly formatted JSON file is now available and automatically updates and we want to load it into the table on the fly when the page is loaded.
This is an example of what were currently use:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
var data = [
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
];
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
</script>
There are a lot more lines of data, the table has CSS styling and applies the sortTable(n) function to the Headers. It displays perfectly, looks and functions like we want,
We've Googled [lots] and tried various load / populate scripts and attempted to get the example on w3schools working - https://www.w3schools.com/js/js_json_html.asp - alas we're fairly new to this.
Our JSON file /assets/sample.JSON is correctly formatted and meets the requirements.
How do we do a simple import of the JSON to populate the table id="gable"?
Ok, so in this solution I am going to assume that your external json file is called 'example.json'
Your external file should look something like this
example.json:
[
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
]
The html remains the same all the changes have been made in the script tags. I split the functionality into 2 new functions. The first function (get_json_data) gets the json data from the external json file. The second function (append_json) appends the data to the table.
I have put comments throughout the code to explain what everything is doing. if you have any questions or if something is unclear let me know.
here is the code for the html file:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
//first add an event listener for page load
document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load
//this function is in the event listener and will execute on page load
function get_json_data(){
// Relative URL of external json file
var json_url = 'example.json';
//Build the XMLHttpRequest (aka AJAX Request)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {//when a good response is given do this
var data = JSON.parse(this.responseText); // convert the response to a json object
append_json(data);// pass the json object to the append_json function
}
}
//set the request destination and type
xmlhttp.open("POST", json_url, true);
//set required headers for the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// send the request
xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
}
//this function appends the json data to the table 'gable'
function append_json(data){
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
}
</script>
you can have a function to create the table independent from your data fields:
function updateTable(tableId, jsonData){
var tableHTML = "<tr>";
for (var headers in jsonData[0]) {
tableHTML += "<th>" + headers + "</th>";
}
tableHTML += "</tr>";
for (var eachItem in jsonData) {
tableHTML += "<tr>";
var dataObj = jsonData[eachItem];
for (var eachValue in dataObj){
tableHTML += "<td>" + dataObj[eachValue] + "</td>";
}
tableHTML += "</tr>";
}
document.getElementById(tableId).innerHTML = tableHTML;
}

export data from Firebase into HTML Table

I'm currently developing an app and using firebase as my database and im trying to export data into a table from a firebase because showing the data in the app in table view is harder than i thought so i turned to HTML table and wrote a code but it is not displaying the data that i want. Just to note that im pretty new to all this so any help would be appreciated. Below is my code:
<html>
<body>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
table {
border-spacing: 5px;
}
</style>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBuJiZZNabXuBO0ac",
authDomain: "",
databaseURL: "",
projectId: "testproject-5",
storageBucket: "",
messagingSenderId: "2568"
};
firebase.initializeApp(config);
</script>
<head>
<title>Quicksol Attendance</title>
</head>
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Employee ID</th>
<th>Email</th>
<th>Date </th>
<th>Check in Time</th>
<th>Check out Time</th>
</table>
<script>
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.employeeID + '</td>';
content += '<td>' + val.email + '</td>';
content += '<td>' + val.date + '</td>';
content += '<td>' + val.checkintime + '</td>';
content += '<td>' + val.checkouttime + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>
</body>
</html>
I have changed the script inside 'database.ref("/").once('value', function (snapshot) {'
Check the working code jsfiddle
// Initialize Firebase
var config = {
apiKey: "AIzaSyBuJiZZNabXuBU-SoRhZFbdecxs0L2O0ac",
authDomain: "testproject-51bd9.firebaseapp.com",
databaseURL: "https://testproject-51bd9.firebaseio.com",
projectId: "testproject-51bd9",
storageBucket: "testproject-51bd9.appspot.com",
messagingSenderId: "256942259748"
};
firebase.initializeApp(config);
var database = firebase.database();
database.ref("/").once('value', function (snapshot) {
if (snapshot.exists()) {
var content = '';
snapshot.forEach(function (data) {
var val = data.val();
var tableData = [];
var sysDate, checkinTime, checkoutTime, email, employeeId;
for (var checkin in val.Checkin) {
for (var date in val.Checkin[checkin]) {
tableData.push({ 'employeeId': checkin, 'email': val.Checkin[checkin][date]['Email'], 'date': date, 'checkinTime': val.Checkin[checkin][date]['Check in Time'] });
}
}
for (var checkout in val.Checkout) {
for (var checkoutDate in val.Checkout[checkout]) {
var item = tableData.find(function (i) { return i.employeeId == checkout && i.date == checkoutDate; })
if (item)
item.checkoutTime = val.Checkout[checkout][checkoutDate]['Checkout Time'];
}
}
console.log(tableData);
tableData.forEach(function (item) {
content += '<tr>';
content += '<td>' + item.employeeId + '</td>';
content += '<td>' + item.email + '</td>';
content += '<td>' + item.date + '</td>';
content += '<td>' + item.checkinTime + '</td>';
content += '<td>' + (item.checkoutTime ? item.checkoutTime : 'NA') + '</td>';
content += '</tr>';
});
});
$('#ex-table').append(content);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-database.js"></script>
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Employee ID</th>
<th>Email</th>
<th>Date </th>
<th>Check in Time</th>
<th>Check out Time</th>
</table>