student.json
{
"student": [
{
"SNo": "1",
"StudentName": "YASHAA BANERJEE",
"AdmissionNo": "01F7001",
"Subject": "Science",
"Class": 01
},
{
"SNo": "2",
"StudentName": "SAKINA KASSIM MATCHESWALA",
"AdmissionNo": "02G7015",
"Subject": "Maths",
"Class": 02
},
{
"SNo": "3",
"StudentName": "AADITHYA PRADEEP",
"AdmissionNo": "02D7021",
"Subject": "Maths",
"Class": 02
}
]
}
index.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function()
{
var students = [];
$.getJSON('students.json', function(data)
{
$.each(data.student, function(i, f)
{
var tblRow = "<tr>" + "<td>" + f.SNo + "</td>" +
"<td>" + f.StudentName + "</td>" + "<td>" + f.AdmissionNo + "</td>" + "<td>" + f.Subject + "</td>" + "<td>" + f.Class + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="page">
<table width="100%" border="0" cellspacing="0" cellpadding="0" height="90%">
<tr valign="top" align="center">
<td>
<table class="data-table" id= "userdata">
<thead>
<tr>
<th>SNo.</th>
<th>Student Name.</th>
<th width='120'>Admission No</th>
<th>Subject</th>
<th>Class</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
In this code I have created a students.json file and index.php file and inside json file I have student data and I want to use json data inside my index.php file but the data are not showing yet I don't know where is the problem ? So, How can I do this ?Please help me.
Thank You
You can see a simple code:
var json = '{"data":[{"SNo":"1","StudentName":"YASHAA BANERJEE","AdmissionNo":"01F7001","Subject":"Science","Class":"1"}]}'
json = JSON.parse(json);
var tb = $("#tab");
$.each(json.data,function(i,value){
tb.append("<tr><td>SNo: " + value.SNo + "</td><td>StudentName: " + value.StudentName + "</td><td>AdmissionNo: " + value.AdmissionNo + "</td><td>Subject: " + value.Subject + "</td><td>Class: " + value.Class + "</td></tr>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tab">
<table>
Related
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.
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);
});
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>
Well, I've been at this for 3 days now and I haven't figured this out yet.
I'm trying to grab the json from this API and trying to parse it to a HTML table, but I'm having trouble. Could anyone help/point me in the right direction?
This is the API I'm trying to grab here
http://census.daybreakgames.com/json/status?game=h1z1
Here's the Code i've tried to do.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var entries = [];
var dmJSON = "http://census.daybreakgames.com/json/status?game=h1z1";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f + "</td>" + "<td>" + f.region_code + "</td>" + "<td>" + f.title + "</td>" + "<td> " + f.status + "</td>" + "<td>" + f.age + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "entrydata" border="1">
<thead>
<th>Name</th>
<th>Region Code</th>
<th>Game</th>
<th>Server Stauts</th>
<th>Time</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
The main reason your code doesnt work is you put a data.entries param for the each function which is undefined. That has to represent a valid key from the json api.
There is two main keys inside the api (for this instance they are Live and Test) so you have to put an each loop inside another one. Then you need to use i to get the name, not f.
var dmJSON = "http://census.daybreakgames.com/json/status?game=h1z1";
$.getJSON(dmJSON, function(data) {
$.each(data.h1z1, function(i, f) {
$.each(f, function(i, f) {
var tblRow = "<tr>" + "<td>" + i + "</td>" + "<td>" + f.region_code + "</td>" + "<td>" + f.title + "</td>" + "<td> " + f.status + "</td>" + "<td>" + f.age + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
});
I have a JSON file with some data.
I can populate a table without an issue, the problem is that I want to format some of the cells with a CSS file and I am stuck. Been trying several ways and none works.
Basically how do I match the json data with each id on the html?
JavaScript
var products=[];
$.getJSON('products.json',function(data){
$.each(data.products, function(i, f){
var tblRow = "<tr><td><img src=" + f.image_url + "></td></tr>" + "<tr><td>" + f.title + "</td></tr>" + "<tr><td>" + f.price + "</td>" + "<td>" + f.old_price + "</td></tr>"
$(tblRow).appendTo("#list_products tbody");
});
});
HTML
<table id="list_products">
<thead>
</thead>
<tbody>
<tr><td id="prod_img"></td></tr>
<tr><td id="title"></td></tr>
<tr>
<td id="price"></td>
<td id="price_org"></td>
</tr>
</tbody>
</table>
JSON
{
"products": [
{
"title": "Revolutionary Mini-UFO (4 pack)",
"image_url": "https://cdn.fyndiq.se/product/fa/87/d7/d871294e94d095743c355b98b827b4a9a0/original.png",
"old_price": "99 kr",
"price": "69 kr",
"price_amount": 69.00
},
Don't use id, since those must be unique and you have "around 20" products. Instead use class. Just add the class names to the code that generates the HTML:
var tblRow = "<tr><td class='prod_img'><img src=" + f.image_url + "></td></tr>" +
"<tr><td class='title'>" + f.title + "</td></tr>" +
"<tr><td class='price'>" + f.price + "</td>" +
"<td class='price_org'>" + f.old_price + "</td></tr>";
Demo:
var products = [{
"title": "Revolutionary Mini-UFO (4 pack)",
"image_url": "https://cdn.fyndiq.se/product/fa/87/d7/d871294e94d095743c355b98b827b4a9a0/original.png",
"old_price": "99 kr",
"price": "69 kr",
"price_amount": 69.00
}];
$.each(products, function(i, f) {
var tblRow = "<tr><td class='prod_img'><img src=" + f.image_url + "></td></tr>" +
"<tr><td class='title'>" + f.title + "</td></tr>" +
"<tr><td class='price'>" + f.price + "</td>" +
"<td class='price_org'>" + f.old_price + "</td></tr>";
$(tblRow).appendTo("#list_products tbody");
});
body {
font-family: sans-serif;
}
.prod_img img {
max-width: 80px;
}
.title {
font-size: 1.25em;
}
.price_org {
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="list_products">
<tbody></tbody>
</table>
To style the dynamic cells (tds), you should assign a class to them, not an id. To do that conditionally, you can use if to check if they meet a condition. Without actual json data, I cannot say more.
Update
If you want to be able to address the bits of data, your trs each should have an id, and the tds a class. If you can control what json to send, I suggest you add an ID (could be a SKU) to each product and use that as an id for the rows:
JSON
"products": [
{
"id": 3812,
"title": "Revolutionary Mini-UFO (4 pack)",
...
},
{
"id": 7155,
"title": ...
...
}
]
JS
var rows = '';
$.getJSON('products.json',function(data){
$.each(data.products, function(i, p){
rows += '<tr id="product_'+p.id+'">';
rows += '<td class="title">'+p.title+'</td>';
rows += '... rest of tds ...';
rows += '</tr>';
});
$("#list_products tbody").append(rows);
});