I'm trying to parse an API json file to an HTML table, i posted the contents of the JSON API file in here for reference: https://pastebin.com/raw/jWaET2TU
For start i wanted to make it simple, just 3 values.
ID | NAME | DESCRIPTION
I can print all data, then when I try to fetch individual values or i get an error or a blank page.
This is all i have till now, but can't figure out what's wrong in the code.
.HTML
<table id="personDataTable">
<tr>
<th>ID</th>
<th>NAME</th>
<th>DESCRIPTION</th>
</tr>
</table>
<style>
table {
border: 2px solid #666;
width: 100%;
}
th {
background: #f8f8f8;
font-weight: bold;
padding: 2px;
}
</style>
.JS
$.ajax({
url: 'https://apiexample.com',
type: "get",
dataType: "json",
success: function(data) {
drawTable(data);
}
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row);
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
row.append($("<td>" + rowData.headline + "</td>"));
}
Related
I am looking to have a + change to a - when my table row expands. I have provided my code below and also through JS Fiddle here: https://jsfiddle.net/k37f0cbp/2/
$(document).ready(function() {
$('tr.parent')
.css("cursor", "pointer")
.attr("title", "click")
.click(function() {
$(this).siblings('.child-' + this.id).toggle();
});
$('tr[#class^=child-]').children('td').hide();
});
$if(('tr[#class^=child-]').is(":visible")).click(function() {
$('.plus', this).html('-');
});
th,
td {
border-bottom: 1px solid black;
}
th,
td {
padding: 15px;
}
tr:hover {
background-color: #f5f5f5;
}
[class*='child-row'] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
<tbody>
<tr class="parent" id="row1" title="click">
<td><span class="plus">+</span></td>
<td>Paper Idea One</td>
</tr>
<tr class="child-row1">
<td>testing</td>
</tr>
</tbody>
</table>
$(document).ready(function ()
{
//add a flag
var expanded = false;
$('tr.parent')
.css("cursor", "pointer")
.attr("title", "click")
.click(function ()
{
$(this).siblings('.child-' + this.id).toggle();
//check flag, update value of a button and update a flag
if(expanded)
{
$(".plus").text("+");
expanded = false;
}
else
{
$(".plus").text("-");
expanded = true;
}
});
$('tr[#class^=child-]').children('td').hide();
});
$if (('tr[#class^=child-]').is(":visible")).click(function()
{
$('.plus', this).html('-');
});
After many more hours exploring this, I combined what the contributor above added with some other things I experimented with and came up with a more elegant and accurate answer that accounts for multiple rows. The only trick here is adding an id to the plus element that is equivalent to the parents id.
$(document).ready(function ()
$('tr.parent')
.css("cursor", "pointer")
.attr("title", "click")
.click(function ()
{
$(this).siblings('.child-' + this.id).toggle();
var s = this.id;
if ($(this).next().is(":visible")) {
$('#' + s + '.plus').html('-');
}
if ($(this).next().is(":hidden")) {
$('#' + s + '.plus').html('+');
}
})
)};
The code below "has been" successfully returning the users.json file in an html table. I modified the json, but the code continues to return the original json. I delete the file, then add it back and then it can't find the file. I have cleared what I thought was the browser cache, to no avail.
Question #1: Where does the server "look" for the users.json file on my web server?
Question #2: How can I assure I'm getting the latest changes, when the user clicks the button?
<script>
function CreateTableFromJSON() {
$.ajax({
type: "get",
url: ***"users.json",***
dataType: "json",
success: function (jsonData) {
var table = $('table');
table.empty();
var name = document.getElementById('name').value.toUpperCase();
$.each(jsonData, function (key, item) {
var table_row = $('<tr>');
$.each(item, function (itemKey, itemValue) {
if (key == 0) {
table.append($('<th>', { html: itemKey }));
}
if (item.LastName.startsWith(name)) {
table_row.append($('<td>', { html: itemValue }));
}
});
table.append(table_row);
}
);
},
error: function () {
alert("json not found");
}
});
}
</script>
<style>
th, td, p, input {
font: 14px Verdana;
}
table, th, td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: left;
}
th {
font-weight: bold;
}
</style>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<input type='text' id='name' placeholder='Search Initial ' />
</div>
<p id="showData"></p>
<table id="tbl"></table>
</body>
</html>
Not sure what you mean by your first question. It will "look" at whatever location is in your url.
For your second question: you want to turn off browser caching. Add "cache: false", eg
type: "get",
url: ***"users.json",***
dataType: "json",
cache: false
I am using data table for displaying data from the database. There is no space between two columns of the data table. How to add space between them. I tried few codes but with no luck...
<html dir="rtl">
<title>moviewall</title>
<style>
#font-face { font-family: "Alef Regular"; src: url("https://s3.eu-central-1.amazonaws.com/moviewall/Alef-Regular.ttf"); }
body { font-family: "Alef Regular", serif }
margin: 0;
font-size: 500%;
font-family: "Alef Regular";
color: white;
line-height: 2.7;
}
</style>
<div id="content"><div dir="ltr">Loading...</div></div>
<script src="lib.js"></script>
<script>
function getHead() {
var row = document.createElement('tr');
['Movie', 'Hall', 'Time'].forEach(function (text) {
var column = document.createElement('th');
column.appendChild(document.createTextNode(text));
row.appendChild(column);
});
return row;
}
function getRow(item) {
var row = document.createElement('tr');
['time', 'hall', 'movie'].forEach(function (property) {
var column = document.createElement('td');
column.appendChild(document.createTextNode(item[property]));
row.appendChild(column);
});
return row;
}
function refreshData() {
var content = document.getElementById('content');
getAllData(function (data) {
clear(content);
var table = document.createElement('table');
table.appendChild(getHead());
data
.filter(function (item) {
var date = new Date();
var minutes1 = date.getHours() * 60 + date.getMinutes();
var minutes2 = convertTimeToMinutes(item.time);
return minutes2 >= minutes1 && minutes2 <= minutes1 + 120;
})
.forEach(function (item) {
table.appendChild(getRow(item));
});
content.appendChild(table);
});
}
setInterval(refreshData, getInterval());
refreshData();
</script>
Blockquote
How can i add space or gap between the columns tr text? 'time', 'hall', 'movie'
Right now they are attached to each other...
Thanks a lot
Shlomi
if you need padding around texts:
td {
padding: 10px;
}
If you want real space between table cells:
td {
border-spacing: 5px;
}
Use border-spacing, see example below:
table {
border-collapse: separate;
border-spacing: 30px 0;
}
td {
border: 1px solid red;
padding: 20px 0;
}
<table>
<tr>
<td>1st column</td>
<td>2nd column</td>
<td>3rd column</td>
<td>4th column</td>
</tr>
</table>
I have a Bootstrap table on the view and the last 2 columns are images. I load the table once the Ajax call is successful.
Issue
when table id populated with data, I see grey border and nothing makes sense. I don't have any code which specifies border.
Below is my CSS Code
img {
border:none;
}
table {
border-collapse:collapse;
}
.assign {
background: url(Images/user_not_assigned.png) no-repeat;
width:100%;
height:40px;
}
I added blue dashed border to the image to make sure it overrides. I see the blue dashed border along with grey border
CSS
img {
border : 2px blue dashed;
border-radius:10px;
padding:5px;
}
table {
border-collapse:collapse;
}
.assign {
background: url(Images/user_not_assigned.png) no-repeat;
width:100%;
height:40px;
}
HTML View:
<div id="getorder" class="table-responsive" data-request-url="#Url.Action("GetPendingOrders", "Main")">
<table id="editorder" class="table table-striped table-hover">
<caption><h4 class="chocolatetext"><strong>Pending / Assigned Orders</strong></h4></caption>
<thead>
<tr>
<th>COL1 #</th>
<th>COL2 #</th>
<th>COL3 #</th>
<th>Assign</th>
<th>Update</th>
</tr>
</thead>
<tbody id="assignorder" data-request-url="#Url.Action("AssignOrder", "Main")">
</tbody>
</table>
</div>
#Scripts.Render("~/Scripts/Custom/main.js")
Jquery Code to load table
$.ajax({
type: 'GET',
url: peningorderurl,
traditional: true,
cache: false,
success: function (data) {
var table = $("table");
table.find("tr:gt(0)").remove(); //remove all previous rows if needed
$.each(data, function (index, element) {
var tr = $("<tr class='clickable-row' data-href=" + element.id + " data-row=" + element.orderno + "></tr>");
table.append(tr);
var td = $("<td>" + element.id + "</td>");
tr.append(td);
var td = $("<td class='testno'>" + element.testno + "</td>");
tr.append(td);
var td = $("<td class='screenno'>" + element.screenno + "</td>");
tr.append(td);
var assignimage = ('<img class="assign assignselected" alt:"Assign Image" />');
if (element.assigned == true) {
assignimage = ('<img class="assigned assignselected" alt:"Assign Image" />');
}
var td = $("<td>" + assignimage + "</td>");
tr.append(td);
assignimage = ('<img class="no-testresults editselected" alt:"Update Test Results" />');
var td = $("<td>" + assignimage + "</td>");
tr.append(td);
});
},
error: function (err) {
alert("Ajax failed:");
console.log(err);
}
});
Question
How do I remove this grey border? Any help would be appreciated.
Change your table CSS to:
table {
border:0;
}
add border 0 on table
table {
border-collapse:collapse;
border:0;
}
Could be background colour coming through?
td {
background-color: #fff;
padding: 0;
}
img {
margin: 0;
display: block;
}
Try using exact specificity for that vs just targeting the table, so try this:
table thead > tr > th { border: none; }
I had the same issue and finally figured it out. The combination of an img Tag and the background property causes this issue. Either use the img tag with src= or use another tag.
Answer found here: css "background-image" shows unwanted border, img "src" does not
I am trying to build an image carousel that uses a Google sheet as the source for the information. I can get the carousel to work if I hard code the JSON, but I am having issues getting the Google Sheet JSON working.
I have opened everything up for viewing that I am working on:
Google Sheet (the script that creates the JSON output can be accessed through Tools/Script Editor)
Google Sheet JSON Output
Google Apps Script Project
Here is the Content Service Web App (generates the JSON from the Google Sheet):
// The name of the spreadsheet from the browser location bar.
// Copy after 'key=' until before the next URL parameter beginning w/&
var SPREADSHEET_ID = '1qolqEsn-hxkRwGfyY1O5ttWB9KzqB7MpgNNF6t3mfvk';
var source = SpreadsheetApp.openById(SPREADSHEET_ID);//Defines the source spreadsheet, in this example, the source is the current spreadsheet.
var source_sheet = source.getSheetByName("Sheet1");//Enter the name between the quotes of the sheet within the specified source spreadsheet that holds the data you want to transfer
var lastRow = source_sheet.getLastRow();//For checking last row with data in cell and formatting range
var lastColumn = source_sheet.getLastColumn();//For checking last row with data in cell and formatting range
var source_range = source_sheet.getRange(1,1,lastRow,lastColumn);//(StartRow,StartColumn,NumberofRowstoGet,NumberofColumnstoGet)
// The name of the sheet, displayed in a tab at the bottom of the spreadsheet.
// Default is 'Sheet1' if it's the first sheet.
var SHEET_NAME = 'Sheet1';
function doGet(request) {
// var callback = request.parameters.jsonp;
var callback = request.parameters.callback;
var json = callback + '(' + Utilities.jsonStringify(source_range.getValues()) + ')';
return ContentService.createTextOutput(json).setMimeType(ContentService.MimeType.JAVASCRIPT);
}
// Testing to see if the jsonp parameter is being used properly.
function testDoGet() {
var request = {parameters: {jsonp: 'callback'}};
var results = doGet(request);
Logger.log(results.getContent());
}
Below is a working code snippet with the hard coded JSON commented out, using the feed from the spreadsheet. Again, the script is fully functional using the hard coded JSON, but does not work when I attempt to use the feed URL.
$(function(){
$.getJSON('https://script.google.com/macros/s/AKfycbzpOcYAX9CrBxGKyQ18Nupe9EzGU-Byl7_A-fY-TSd1zbcvAw/exec?callback=?',
function(json) {
// console.log(json); //Testing
// console.log(json[0][0]); //Testing
var mhtml = '<ul>';
for (var i = 1; i < json.length; i++){ //For each item in the json array
// console.log('image: ' + json[i][0]); //Log the array field
// console.log('title: ' + json[i][1]); //Log the array field
// console.log('desc: ' + json[i][2]); //Log the array field
mhtml += '<li><div class="img-responsive"><img src="https://images1-focus-opensocial.googleusercontent.com/gadgets/proxy?url='+json[i][0]+'&container=focus&resize_w=665" /></div>';
mhtml += '<div class="desc"><h1 class="title">'+json[i][1]+'</h1>';
mhtml += '<p class="expert">'+json[i][2]+'</p></div>';
mhtml += '</li>';
};
mhtml += '</ul>';
$('.slider').append($(mhtml));
slideshow();
});
function slideshow() {
// console.log('running slideshow'); //Testing
// console.log('slider length: ' + $(".slider ul> li").length); //Testing
$(".slider ul> li:gt(0)").css("opacity" , "0");
var j = 0;
var delay = 3000; //millisecond delay between cycles
function cycleThru(){
var jmax = $(".slider ul> li").length -1;
$(".slider ul> li:eq(" + j + ")")
.animate({"opacity" : "1.0"} ,400)
.animate({"opacity" : "1"}, delay)
.animate({"opacity" : "0"}, 400,
function(){
(j == jmax) ? j=0 : j++;
cycleThru();
});
};
cycleThru();
}
});
#import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:400,700);
*{
margin: 0;
padding: 0;
font-family: 'Yanone Kaffeesatz';
}
h1 {
font-size: 3em;
font-family: arial;
}
p {
font-size: 1em;
font-family: arial;
}
ul li { margin: 0;
padding: 0;list-style:none}
.slider {
display: block;
min-height: 345px;
max-width: 665px;
margin: auto;
border: 12px rgba(255,255,240,1) solid;
-webkit-box-shadow: 0px 0px 5px rgba(0,0,0,.8);
-moz-box-shadow: 0px 0px 5px rgba(0,0,0,.8);
box-shadow: 0px 0px 5px rgba(0,0,0,.8);
margin-top: 20px;
position: relative;
}
.slider ul{
display: block;
height: auto;
max-width: 640px;
overflow:hidden}
.slider>ul>li {
height: 320px;
float: left;
position: absolute;
}
.slider >ul>li>img {
margin: auto;
height: 100%;
min-height: 345px;
max-width: 665px;
}
.desc {
position: absolute;
bottom: 0;
left: 0;
width: 260px;
z-index: 1000;
background-color: rgba(255,255,240,0.5);
display: inline-block;
text-align: center;
padding-top: 7px;
border-top-right-radius: 15px;
border-bottom-right-radius: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://storage.googleapis.com/code.getmdl.io/1.0.4/material.min.js"></script>
<?!= include('css'); ?>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" />
</head>
<body>
<div class="slider"></div>
</body>
</html>
You need to add the callback parameter to your URL.
$.getJSON('https://script.google.com/macros/s/AKfycbzpOcYAX9CrBxGKyQ18Nupe9EzGU-Byl7_A-fY-TSd1zbcvAw/exec?callback=?', ...
In your contentservice app:
function doGet(request) {
var callback = request.parameters.callback;
var json = callback + '(' + Utilities.jsonStringify(source_range.getValues()) + ')';
return ContentService.createTextOutput(json).setMimeType(ContentService.MimeType.JAVASCRIPT);
}
I have this working now and have updated the code above. Thanks to #spencer-easton for helping with the JSON. Once I got the feed working, I had to make changes to get it to work. Significant changes to the original code to highlight are:
Added a for loop to iterate through the array that results from the JSON:
for (var i = 1; i < json.length; i++){ //For each item in the json array
mhtml += '<li><div class="img-responsive"><img src="https://images1-focus-opensocial.googleusercontent.com/gadgets/proxy?url='+json[i][0]+'&container=focus&resize_w=665" /></div>';
mhtml += '<div class="desc"><h1 class="title">'+json[i][1]+'</h1>';
mhtml += '<p class="expert">'+json[i][2]+'</p></div>';
mhtml += '</li>';
};
Removed $(document).ready from the function that cycled the carousel, and instead called it at the end of the json response function:
$('.slider').append($(mhtml));
slideshow();
});
function slideshow() {
$(".slider ul> li:gt(0)").css("opacity" , "0");
var j = 0;
var delay = 3000; //millisecond delay between cycles
function cycleThru(){
var jmax = $(".slider ul> li").length -1