Really stupid question here, but I'm trying to display some JSON data in an HTML page. I'm more of a backend person (Bash) and only know basic HTML. I'd like to perform the Bash equivalent of storing data into a variable and calling it again later. Can I do that with Javascript/HTML? I have the rough code below, but I'd like to return some data in different points all over the page, not just in a list.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
<div id="placeholder"></div>
<script>
$.get( "https://chain.so/api/v2/get_price/BTC/USD", function( response ) {
$( "body" )
.append("Network: " + response.data.network + "<br/>" )
.append("Price: " + response.data.prices[0].price + "</br>")
.append("Exchange: " + response.data.prices[0].exchange+ "</br>")
.append("Price: " + response.data.prices[1].price + "</br>")
.append("Exchange: " + response.data.prices[1].exchange+ "</br>")
.append("Price: " + response.data.prices[3].price + "</br>")
.append("Exchange: " + response.data.prices[3].exchange+ "</br>");
}, "json" );
</script>
</body>
</html>
For example, I'd like to show the data at different points in the page. Is that possible?
<!DOCTYPE html>
<html>
<body>
<h2>Heading1</h2>
<ul style="list-style-type:disc">
<li>Test1</li>
<li>**JSON DATA HERE**</li>
<li>Test3</li>
</ul>
<h2>Heading2</h2>
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>
<tr>
<td>Thing1</td>
<td>**JSON DATA HERE**</td>
<td>**JSON DATA HERE**</td>
</tr>
<tr>
<td>Thing2</td>
<td>**JSON DATA HERE**</td>
<td>**JSON DATA HERE**</td>
</tr>
<tr>
<td>Thing3</td>
<td>**JSON DATA HERE**</td>
<td>**JSON DATA HERE**</td>
</tr>
</table>
</body>
</html>
Many ways this could be achieved. Example:
$.get( "https://chain.so/api/v2/get_price/BTC/USD", function( response ) {
$("#network").text(response.data.network);
$.each(response.data.prices, function(i, val) {
$("#thing" + i + "price").text(val.price);
$("#thing" + i + "exchange").text(val.exchange);
});
}, "json" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Heading1</h2>
<ul style="list-style-type:disc">
<li>Test1</li>
<li><span id="network"></span></li>
<li>Test3</li>
</ul>
<h2>Heading2</h2>
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>
<tr>
<td>Thing1</td>
<td><span id="thing0price"></span></td>
<td><span id="thing0exchange"></span></td>
</tr>
<tr>
<td>Thing2</td>
<td><span id="thing1price"></span></td>
<td><span id="thing1exchange"></span></td>
</tr>
<tr>
<td>Thing3</td>
<td><span id="thing2price"></span></td>
<td><span id="thing2exchange"></span></td>
</tr>
</table>
if I understand it correct, from your example, you can populate that data in your heading and table as follows
$.get( "https://chain.so/api/v2/get_price/BTC/USD", function( response ) {
$( "ul > li" )[1].html(response.data.network);
var tableHtml = '';
var prices = response.data.prices;
for(i=0;i<prices.length;i++){
tableHtml += '<tr>';
tableHtml += '<td>Thing '+i+'</td>';
tableHtml += '<td>'+prices[i].price +'</td>';
tableHtml += '<td>'+prices[i].exchange +'</td>';
tableHtml += '</tr>';
}
$('<table>').remove();//To remove any old table
$('<table>'+tableHtml+'</table>').insertAfter('h2');
}, "json" );
Related
This question already has answers here:
How do I force jQuery append to NOT automatically close a tag?
(3 answers)
Closed 1 year ago.
im doing an ajax call and getting alot of results from DB and then im using jquery to loop them and do a simple table. The problem is that the loop is puting the results outside the <table> and outside <tbody> and is creating a tbody in the top of everything. I know the current results are static its just for testing and i know JS is synchronous, so i cant understand whats the problem.
My code:
$('#' + id).append('' +
'<table class="documents_table">'+
'<tbody">'+
'<tr>'+
'<th>number</th>'+
'<th>Date</th>'+
'<th> Cód</th>'+
'<th> Terce</th>'+
'</tr>'
);
$.each(data.responseJSON, function (index, value) {
$('#' + id).append('' +
'<tr">'+
'<td>1</td>'+
'<td>12/98/2021</td>'+
'<td>1212</td>'+
'<td>test it</td>'+
'</tr>'
);
}).$('#' + id).append(''+
'</tbody>'+
'</table>'
);
how is the current output:
<tbody"></tbody">
<table class="documents_table">
<tbody>
<tr>
<th>number</th>
<th>Date</th>
<th> Cód</th>
<th> Terce</th>
</tr>
</tbody>
</table>
<tr>
<td>1</td>
<td>12/98/2021</td>
<td>1212</td>
<td>test it</td>
</tr>
<tr>
<td>1</td>
<td>12/98/2021</td>
<td>1212</td>
<td>test it</td>
</tr>
<tr>
<td>1</td>
<td>12/98/2021</td>
<td>1212</td>
<td>test it</td>
</tr>
.........
What's happening is jquery is "being helpful"(tm).
When you append <table> it "helpfully" closes the tag for you, so actually outputs <table></table>.
Build your entire table with a single string then have a single .append at the end
var html =
'<table class="documents_table">'+
'<tbody">'+
'<tr>'+
'<th>number</th>'+
'<th>Date</th>'+
'<th> Cód</th>'+
'<th> Terce</th>'+
'</tr>';
$.each(data.responseJSON, function (index, value) {
html +=
'<tr>'+
'<td>1</td>'+
'<td>12/98/2021</td>'+
'<td>1212</td>'+
'<td>test it</td>'+
'</tr>';
}).
html +=
'</tbody>'+
'</table>';
$('#' + id).append(html);
I´m done in updating the cell and now I want to refresh automatically the tag after i click the button looped by on the table using google-app-script. Cannot understand the coding in the documentation. Please help me to solve this. Thanks!
html
<div id="tables">
<? var data = getData();?>
<table id="tableShift1">
<caption style="">Shift1</caption>
<th> ID </th>
<th> Ldap </th>
<th> Action </th>
<? for (var dataList = 1; dataList < data.length; dataList++) {
if (data[dataList][2] == '') {?>
<tr >
<td><?= data[dataList][0] ?></td>
<td><?= data[dataList][1] ?></td>
<td><button onclick='google.script.run.setApproved("<?=data[dataList][0]?> ","<?=data[dataList][1]?>")' id='btnApprove'>Approve</button></td>
</tr>
<? }
} ?>
</table>
<table id="tableShift2">
<caption>Shift2</caption>
<th> ID </th>
<th> Ldap </th>
<th> Action </th>
</table>
</div>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(showData)
.getData();
});
function showData(things2) {
var table = $('#tableShift2');
var kwit = ',';
for (var i = 1; i < things2.length; i++) {
table.append('<tr ><td>' + things2[i][0] +
'</td><td style=>' + things2[i][1]+ things2[i][0] +
'</td><td ><button onclick="google.script.run.setApproved("'+ things2[i][0] +'","'+ things2[i][1] +'")" id="btnApprove">Approve</button></td></tr>');
}
}
</script>
</body>
You might try something like this:
Add and new function that provides the ability to return new data to refreshData()
function showData(things2) {
var table = $('#tableShift2');
var kwit = ',';
for (var i = 1; i < things2.length; i++) {
table.append('<tr ><td>' + things2[i][0] +
'</td><td style=>' + things2[i][1]+ things2[i][0] +
'</td><td ><button onclick="ApproveAndRefresh("'+ things2[i][0] +'","'+ things2[i][1] +'");" id="btnApprove">Approve</button></td></tr>');
}
}
function ApproveAndRefresh(data1,data2){//you may need to include i
google.script.run
.withSuccessHandler(refreshData)
.setApproved1(data1,data2);//a modified setApproved on the server that returns the appropriate html to the tableShift2 element
}
function refreshData(hl){
document.getElementById('tableShift2').innerHTML=hl;
}
I have an HTML table which is populated in my JSP view. This table always contains data of the default today date. The data is retrieved by an automatic batch that fetch data from a database. However i have to give a functionnality to be able to select data on a daterange. This is why I use a daterangepicker. I succeeded to apply to datefilter with ajax calls.
What I want to do is to now when I select a new DateRange i update my already HTML table with the default date with Data from the selected date to replace the old data with new data in my table
Here is my JSP page with the table i want to update when i Select a DATERANGE:
<div class="panel-body">
<table width="100%"class="table table-striped table-bordered table-hover" id="tableUp">
<thead>
<tr>
<th>FormName</th>
<th>Type</th>
<th>Language</th>
<th>Sent To NAS</th>
<th>Sending Date</th>
<th>FeedBack Received</th>
<th>Feedback not Received</th>
</tr>
</thead>
<tbody id='tbod'>
<tr class="odd gradeX" id="myTable">
<c:forEach var="item" items="${eblinb2b_list}">
<tr id=1>
<td><c:out value="${item.form_name}" /></td>
<td><c:out value="${item.mode}" /></td>
<td><c:out value="${item.language}" /></td>
<td><c:out value="${item.count}" /></td>
<td><c:out value="${item.sendingDate}" /></td>
<td><c:out value="" /></td>
<td><c:out value="" /></td>
</tr>
</c:forEach>
</tr>
</tbody>
</table>
</div>
For the purpose of understanding a put here a new table in the lower part of my JSP view so that you understand:
<!-- DateRange PICKER -->
<div class="panel-body">
<table width="100%" class="class2" id="mainTable">
<thead>
<tr>
<th>FormName</th>
<th>Type</th>
<th>Language</th>
<th>Sent To NAS</th>
<th>Sending Date</th>
<th>FeedBack Received</th>
<th>Feedback not Received</th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX" id="myTable1"></tr>
</tbody>
</table>
<input type="text" name="datepickerinput" id="datepicker" value="" />
</div>
<!-- /.panel-body -->
<button onclick="filterByDate()" id="button">Apply filter</button>
Here is my JavaScript function part that populate my second table for illustrating
**//Function for populating second table with Ajax JSON response**
var table = $("#mainTable tbody");
$.each(data, function(idx, elem) {
var time = new Date(elem.sendingDate);
var parsedTime = time.getDate() + "/" + (time.getMonth() + 1) + "/"
+ time.getFullYear();
table.append("<tr><td>" + elem.form_name + "</td><td>"
+ elem.mode + "</td><td>" + elem.language
+ "</td><td>" + elem.count + "</td><td>"
+ parsedTime + "</td></tr>");
I finally succeeded to manage the problem this is my final function that updates the table by putting the data and replacing the old one:
function prepareTable(data) {
//Function for populating table with Ajax JSON response
var table = $("#tableUp #tbody1");
var html = "";
$.each(data, function(idx, elem) {
var time = new Date(elem.sendingDate);
var parsedTime = time.getDate() + "/"
+ (time.getMonth() + 1) + "/"
+ time.getFullYear();
html += "<tr><td>" + elem.form_name + "</td><td>"
+ elem.mode + "</td><td>" + elem.language
+ "</td><td>" + elem.count + "</td><td>"
+ parsedTime + "</td><td></td><td></td></tr>";
});
table.html(html);
}
The prepareTable() function is triggered (called) when the Ajax call succeeded:
function filterByDate() {
var startDate = document.getElementById("datepicker").value
.substring(0, 10);
var endDate = document.getElementById("datepicker").value
.substring(13, 23);
$.ajax({
url : '/gms/eblinb2b/filterOnDate',
data : {
"startDate" : startDate,
"endDate" : endDate
}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
//here you will see displaying the callback result coming from your spring controller
console.log(data);
//Here we populate the HTML table with the new data based on the new daterange filter applied and replace the old data in my table
prepareTable(data);
},
error : function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}
I am trying to fill html table(my table got 3 columns) with data from json using javascript but the data never get filled using div method! could any tell me how to fill content of table rows using without using div ?
for(i in json)
{
var div = "<tr id=\""+i+"\">\n" +
"<td>"+i+"</td>\n" +
"<td><img src=\""+ json[i].thumb +"\" height=\"42\" width=\"42\"></td>\n" +
"<td>\n" +
"" + json[i].title + "<br> \n" +
"<br></td></tr>\n\n";
$("#myDiv").append(div);
}
Table to be filled:
<table id="list" cellspacing="0" border="1">
<tr>
<th>Item#</th>
<th>Logo</th>
<th>Description</th>
</tr>
<div id='myDiv'></div>
</table>
This Your new table:
<table id="list" cellspacing="0" border="1">
<thead>
<tr>
<th>Item#</th>
<th>Logo</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And code:
var html = '';
for(var i in json)
{
html += '<tr id="'+i+'">';
html += '<td>'+i+'</td>';
html += '<td><img src="'+json[i].thumb+'" height="42" width="42"></td>';
html += "<td>";
html += "" + json[i].title + "<br/><br/>";
html += '</td>';
html += '</tr>';
}
$('#list > tbody').html(html);
I'm trying to mirror a table, with a dynamic grid like 4x4, 7x7, or 9x2.
I dynamically create this:
<table id="mainTable" class="mainClassTable" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr id="row-1">
<td id="col-1" onclick="imgClick(this)">Stuff Here</td>
<td id="col-2" onclick="imgClick(this)">Stuff Here</td>
<td id="col-3" onclick="imgClick(this)">Stuff Here</td>
<td id="col-4" onclick="imgClick(this)">Stuff Here</td>
</tr>
<tr id="row-2">
<td id="col-1" onclick="imgClick(this)">Stuff Here</td>
<td id="col-2" onclick="imgClick(this)">Stuff Here</td>
<td id="col-3" onclick="imgClick(this)">Stuff Here</td>
<td id="col-4" onclick="imgClick(this)">Stuff Here</td>
</tr>
<tr id="row-3">
<td id="col-1" onclick="imgClick(this)">Stuff Here</td>
<td id="col-2" onclick="imgClick(this)">Stuff Here</td>
<td id="col-3" onclick="imgClick(this)">Stuff Here</td>
<td id="col-4" onclick="imgClick(this)">Stuff Here</td>
</tr>
</tbody>
</table>
I'm wondering what would be the best way for each row to get col-1 to move to col-4, and col-2 on col-3. And with uneven columns I fear it would be more complicated.
I found something about shuffling rows, but I want to shuffle columns.
I'm thinking about using jQuery selectors to tediously repositioning each td, but i'm wondering if there might be a nice jquery plugin to rearrange tables.
I don't want draggable, I just want one click to mirror the table (not the contents).
/Edit
So I tried making each col ID unique, but I ended up with this steaming pile of code:
function makeGrid(content, rowCount, colCount)
{
//Empty TD string
tableVarSet = "";
//gridTotal = gridTotal - gridTotal;
//Loop for multiple columns
for (c=1;c<=colCount;c++)
{
//make column var
tableVarSet = tableVarSet + makeColumns(content, c);
}
//Loop for multiple rows
for (i=1;i<=rowCount;i++)
{
//Make new Row
rowVarToAdd = "<tr id=TMPR>"+tableVarSet+"</tr>";
$("#mainTable").append(rowVarToAdd);
//Set new RowID
rowName = "row-" + i;
$("#TMPR").attr('id', rowName);
}
};
function makeColumns(content, count)
{
//Split String
tableVar1 = "<td id=col-"
tableNum = count;
tableVar2 = " onClick='imgClick(";
tableFunction = "this" ;
tableVar3 = ")'>"+content+"</td>";
//Combine Strings:
colVar = tableVar1 + tableNum + tableVar2 + tableFunction + tableVar3;
//Return result
return colVar;
};
So, yeah it kind of works but It can probably be a lot easier. (any ideas?)
Instead of using strings, consider DOM manipulation.
var rows = document.getElementById("mainTable").rows, cells, fragment = document.createDocumentFragment();
for(var i = 0, len = rows.length; i<len; i++){ //Iterate over each row
cells = rows[i].cells;
for(var j = cells.length-1; j>=0; j--) {
fragment.appendChild(cells[j]); //Remove the cells starting from the end and put them in a document fragment
}
rows[i].appendChild(fragment); //Append the fragment's contents to the current row
}
Demo on jsFiddle
First you should not be using multiple ID's with the same value! You should use classes.
Second of all, the below code works but you will need to change it to suit your application.
If you don't want the contents copied just remove the html() call on each of the cells.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<table id="test">
<tr id="row-1"><td class="col-1">col 1</td><td class="col-2">col 2</td><td class="col-3">col 3</td></tr>
<tr id="row-2"><td class="col-1">col 1</td><td class="col-2">col 2</td><td class="col-3">col 3</td></tr>
<tr id="row-3"><td class="col-1">col 1</td><td class="col-2">col 2</td><td class="col-3">col 3</td></tr>
</table>
</body>
<div id="mirror"></div>
<script type="text/javascript">
var table = $('#test');
var OUTPUT = '<table id="test">';
for (var i = 1; i <= $('#test tr').length; i++){
OUTPUT += '<tr id="row-' + i + '">';
OUTPUT += '<td class="col-1">' + $('#row-' + i + " .col-3").html() + '</td>' + "\n";
OUTPUT += '<td class="col-2">' + $('#row-' + i + " .col-2").html() + '</td>' + "\n";
OUTPUT += '<td class="col-3">' + $('#row-' + i + " .col-1").html() + '</td>' + "\n";
OUTPUT += '</tr>';
};
OUTPUT += '</table>';
$('#mirror').html(OUTPUT);
</script>
</html>