I need to insert some values in a table. All values are contained in a returned array from an Ajax/php request like this:
var data = [];
//Consider that the number of the object (in this case only 3) obtained from the server are equal to the number of rows in tbody (6 rows in tbody = 6 object from server).
data[0] = {From: '01/01/2012', To: '01/01/2013', Interest: 80.00, Residual: 0, Capital: 1000.00, Days: 366};
data[1] = {From: '01/01/2013', To: '01/01/2014', Interest: 85.00, Residual: 0, Capital: 980.00, Days: 365};
data[2] = {From: '01/01/2014', To: '29/04/2014', Interest: 20.00, Residual: 75.00, Capital: 980.00, Days: 118};
It's a bit tricky to explain how the values must to be inserted in the table, so I created a fiddle with the result I would like to get.
I do not expect you to give me the final result (of course, would be welcome :) ), but at least some idea from which to start.
FIDDLE
**EDIT
I assigned id to cells and now all values are right inserted. That's the updated fiddle, do you think code can be written more elegantly?
UPDATE FIDDLE
I can see the data returned from ajax/php request is in JSON format. So to insert them in HTML table you can use JQuery.
Example (as you given sample data):
function buildDataTableHtml(data){
var tableHtml = "<table><tr>";
tableHtml += "<th>From</th>";
tableHtml += "<th>To</th>";
tableHtml += "<th>Interest</th>";
tableHtml += "<th>Residual</th>";
tableHtml += "<th>Capital</th>";
tableHtml += "<th>Days</th>";
tableHtml += "</tr>";
$.each(data, function(i, v){
tableHtml += "<tr>";
tableHtml += "<td>" + v.From + "</td>";
tableHtml += "<td>" + v.To + "</td>";
tableHtml += "<td>" + v.Interest + "</td>";
tableHtml += "<td>" + v.Residual + "</td>";
tableHtml += "<td>" + v.Capital + "</td>";
tableHtml += "<td>" + v.Days + "</td>";
tableHtml += "</tr>";
});
tableHtml += "</table>";
return tableHtml;
}
If you use this JavaScript function (along with JQuery) then this function will return the HTML of a table you wanted. Hope this will be helpful for you
NOTE: I just write it down in answer box, didn't try to make sure this is working. But hope the code will work. :)
Related
Using this example https://www.jqueryscript.net/table/jQuery-Plugin-To-Generate-A-Table-From-A-CSV-File-CSV-Parser.html
I set up a HTML table that takes a CSV file from multiple Raspberry PIs (via SSH) and displays this CSV output as a HTML table:
2018-03-22 12:43:21,NM_Test.h264,-2
My HTML page runs the following script:
<!DOCTYPE html>
<body>
<div id="container"></div>
<script>
$.get('ssh.php', function(data) {
// start the table
var html = '<table">';
// split into lines
var rows = data.split("\n");
// parse lines
rows.forEach( function getvalues(ourrow) {
// start a table row
html += "<tr>";
// split line into columns
var columns = ourrow.split(",");
html += "<td>" + columns[0] + "</td>";
html += "<td>" + columns[1] + "</td>";
html += "<td>" + columns[2] + "</td>";
// close row
html += "</tr>";
})
// close table
html += "</table>";
// insert into div
$('#container').append(html);
});
</script>
</body>
</html>
My SSH.php:
// set up SSH2 conenctions using config.php to connect to multiple PIs and execute:
echo $ssh->exec('tail -1 /var/log/playlog.csv');
Config.php:
return [
[
"name" : "test1",
"ip" : "127.0.0.1",
"port": 97,
"key" : 'ssh-dss AAAAB3NzaC1kc3MAA...c3=',
]
[ ... ]
];
In my HTML table how can I add column names such as:
<tr>
<th>PI Name</th>
<th>Date/Time</th>
<th>Playing</th>
<th>Error</th>
</tr>
But for the 'PI Name' column how can I return the corresponding 'name' that I have defined for each PI inside my config.php file?
I'm having difficulty with using HTML tags inside jQuery.
The easiest way is to add the PI name as the first element in each row of your CSV file, so in PHP code not in JavaScript code.
CSV file should look like that:
test1,2018-03-22 12:43:21,NM_Test.h264,-2
After you adjusted CSV format, make this JavaScript changes:
<script>
$.get('ssh.php', function(data) {
// start the table
var html = '<table>';
// add column headers
html += '<tr><th>PI Name</th><th>Date/Time</th><th>Playing</th><th>Error</th></tr>';
// split into lines
var rows = data.split('\n');
// parse lines
rows.forEach( function getvalues(ourrow) {
// start a table row
html += "<tr>";
// split line into columns
var columns = ourrow.split(",");
html += "<td>" + columns[0] + "</td>";
html += "<td>" + columns[1] + "</td>";
html += "<td>" + columns[2] + "</td>";
html += "<td>" + columns[3] + "</td>";
// close row
html += "</tr>";
})
// close table
html += "</table>";
// insert into div
$('#container').append(html);
});
</script>
I am working on a small project's interface. Basically, an API sends the following JSON data:
{
"wallet_transactions": [
{
"total_cost": "80.000",
"expense_type__name": "Gas",
"total_quantity": "5.000",
"trans_type": "Purchased"
},
{
"total_cost": "250.000",
"expense_type__name": "Gas",
"total_quantity": "35.000",
"trans_type": "Rent"
}
]}
The data basically shows how much of GAS was given, its cost and its means (on credit or it was bought).
I tried to build a table out of it directly, but it was dimmed unfriendly since GAS was written twice.
What I tried was:
$.each(response.wallet_transactions, function(index) {
var exp_name=response.wallet_transactions[index].expense_type__name;
var quantity=response.wallet_transactions[index].total_quantity;
var price=response.wallet_transactions[index].total_cost;
var trans_type=response.wallet_transactions[index].trans_type;
rows=rows+'<tr><td>' + exp_name + '</td>';
rows=rows + '<td>' + price + '</td>';
rows=rows + '<td>' + quantity + '</td>';
rows=rows + '</tr>';
});
The output that is needed now looks like the image below:
Group the data for each name together in another object, then build the table from that.
var table_data = {};
$.each(response.wallet_transactions, function(i, trans) {
var exp_name = trans.expense_type__name;
var quantity = trans.total_quantity;
var price = trans.total_cost;
var trans_type = trans.trans_type;
if (!table_data[exp_name]) {
table_data[exp_name] = {}
}
table_data[exp_name][trans_type] = {
quantity: quantity,
cost: price
};
}
$.each(table_data, function(name, data) {
rows += "<tr><td>" + name + "</td>";
rows += "<td>" + data.Rent.cost + "</td>";
rows += "<td>" + data.Rent.quantity + "</td>";
rows += "<td>" + data.Purchased.cost + "</td>";
rows += "<td>" + data.Purchased.quantity + "</td>";
rows += "</tr>";
}
Notice that $.each passes the array element as the second argument to the callback function, so you don't have to repeat response.wallet_transactions[index] on every line.
I have got the current code https://jsfiddle.net/rjw3f7yu/5/ that can plot table in HTML using Javascript code. However, there is this line that pops up stating "undefined" between row 1 and 2. Anyone knows what could be the problem here?
I am using bootstrap v3 just for extra info. Thanks!
HTML code:
<table class="table" id="wconclusiontable">
</table>
Javascript Code:
var counttopercentagec1event = [0, 1, 2, 3, 4, 5];
var counttopercentagec2event = [2, 33, 22, 32, 43, 52];
var counttopercentagec3event = [7, 17, 72, 37, 47, 51];
function wconclusiontable() {
var wtable = document.getElementById("wconclusiontable");
var row;
row += "<thead><tr><th>" + "Event #" + "</th>";
row += "<th>" + "Low" + "</th>";
row += "<th>" + "Medium" + "</th>";
row += "<th>" + "High" + "</th>";
row += "</tr></thead>";
for (var i = 2; i < 5; i++) {
row += "<tbody><tr><td>" + (i-1) + "</td>";
row += "<td>" + counttopercentagec1event[i-1] + "%" + "</td>";
row += "<td>" + counttopercentagec2event[i-1] + "%" + "</td>";
row += "<td>" + counttopercentagec3event[i-1] + "%" + "</td>";
row += "</tr></tbody>";
}
wtable.innerHTML = row;
}
wconclusiontable();
You have to initialise var row with empty string. Since row is undefined initially and you're adding directly with string, the initial row variable's value undefined is getting added. Hope that helps
Update fiddle - https://jsfiddle.net/rjw3f7yu/6/
var row = '';
It's probably because you never initialize your variable, "row". Initially, row is therefore undefined.
When you add to it the first time, you'll basically concatenate the strings "undefined" with "Event #".
Try defining row as:
var row = "";
Your updated code:
function wconclusiontable() {
var wtable = document.getElementById("wconclusiontable");
var row = "";
row += "<thead><tr><th>" + "Event #" + "</th>";
row += "<th>" + "Low" + "</th>";
row += "<th>" + "Medium" + "</th>";
row += "<th>" + "High" + "</th>";
row += "</tr></thead>";
for (var i = 2; i < 5; i++) {
row += "<tbody><tr><td>" + (i-1) + "</td>";
row += "<td>" + counttopercentagec1event[i-1] + "%" + "</td>";
row += "<td>" + counttopercentagec2event[i-1] + "%" + "</td>";
row += "<td>" + counttopercentagec3event[i-1] + "%" + "</td>";
row += "</tr></tbody>";
}
wtable.innerHTML = row;
}
Declaring a variable in a function in JavaScript generally serves one purpose - to set the scope of that variable, and avoid collision with a global variable. Since JavaScript is dynamically typed, JavaScript has no clue what it should be initializing your variable to at first. So, it chooses to define it as an "undefined" object.
During string concatenation, JavaScript will type coerce all objects involved in the operation to a string. This includes "undefined".
Why, then, does undefined appear after the header of the table? This happens because HTML renders the thead of the table before anything else. The best way to figure out what the potential issue is when dealing with a JavaScript issue like this is to open the inspector by right clicking the problematic element on the page and choosing "Inspect Element".
var row;
Replace above line by this
var row = new String("");
https://jsfiddle.net/wxaty4xs/
I need to implement drag and drop feature form one table to another and vise versa.
This is my function where i get transactions to particular IBAN number, I also have the same function which retrieves users transaction which are hidden.
function getAllTransactions(iban) {
var iban = $("#ibanSelection").val();
var username = $("#hiddenusername").val();
var url = 'http://localhost:64300/api/BankAccountApi/GetUserTransaction/?iban=' + iban;
var table = "<table id=\"table1\">";
if ((username != "") && (iban !="")) {
$.getJSON(url, function (data) {
table += "<tr class=\"ibanSelection\">";
table += "<th>My IBAN</th>";
table += "<th>Send to IBAN</th>";
table += "<th>Transfer Date</th>";
table += "<th>Amount</th>";
table += "</tr>";
$.each(data, function (key, val) {
table += "<tr class=\"draggable_tr\">";
table += "<td>" + val.My_Iabn + "</td>";
table += "<td>" + val.Iban_To + "</td>";
table += "<td>" + val.Transfer_Date + "</td>";
table += "<td>" + val.Amount_Transferd + "</td>";
table += "</tr>";
});
table += "</table>";
$("#divResult2").html(table);
});
}
}
Just use the jQueryUI Sortable feature.
Here's the complete example + documentation. Very easy.
Also this example shows your case:
http://jqueryui.com/sortable/#connect-lists
First time poster here and new to JavaScript...
Below is my JSON object...
[
{
"Name":"Ted",
"EmailAddress":"ted#ted.edu",
"Title":"Director",
"Expertise":"Statistics",
"PhoneNumber":"444-444-4444"
},
{
"Name":"Ann",
"EmailAddress":"ann#ann.edu",
"Title":"Director",
"Expertise":"Physics",
"PhoneNumber":"444-444-5555"
}
]
What I need is to be able to loop through this to add each table row for each employee. There are five values: Name, EmailAddress, Title, Expertise, PhoneNumber
This is what I have so far...
$(function () {
var Employees= [{"Name":"Ted","EmailAddress":"ted#ted.edu","Title":"Director","Expertise":"Statistics","PhoneNumber":"444-444-4444"}, {"Name":"Ann","EmailAddress":"ann#ann.edu","Title":"Director","Expertise":"Physics","PhoneNumber":"444-444-5555"}];
$("#pager").append("<table id='employeelist' class='table'><table>");
//for loop goes here//
Any help would be appreciated!
EDIT: Also, how would I make the e-mail addresses 'clickable'/'mail to' the address?
A simple loop will do, you should also build the entire HTML string, then append:
var table = "<table id='employeelist' class='table'>";
for (var i = 0; i < Employees.length; i++) {
//Create the table row
table += "<tr>";
//Create table cells
table += "<td>" + Employees[i].Name + "</td>";
table += "<td>" + Employees[i].EmailAddress + "</td>";
table += "<td>" + Employees[i].Title + "</td>";
table += "<td>" + Employees[i].Expertise + "</td>";
table += "<td>" + Employees[i].PhoneNumber + "</td>";
//Close table row
table += "</tr>";
}
table += "</table>";
$("#pager").append(table);
Since JSON objects are just normal Javascript objects, you can treat them as such.
For example, in order to loop over them you could just do normal Javascript loop:
for(var i = 0; i < Employees.length; i++) {
var employee = Employees[i];
}
and then, in order to access information from an employee, you can just do employee.Name to access it's name, employee.Title for the title etc.
Using the information in employee.Name and the others, you can simply build your strings using that information:
str += '<td>' + employee.Name + ...
and then finally append it with $("#pager").append(str);.
'Welcome to Stackoverflow and javascript :)'
It is actually a javascript object ( not JSON object ).
$(function() {
var Employees = [{
"Name": "Ted",
"EmailAddress": "ted#ted.edu",
"Title": "Director",
"Expertise": "Statistics",
"PhoneNumber": "444-444-4444"
}, {
"Name": "Ann",
"EmailAddress": "ann#ann.edu",
"Title": "Director",
"Expertise": "Physics",
"PhoneNumber": "444-444-5555"
}];
var table = '<table id="employeelist" class="table">';
for (var i = 0, j = Employees.length; i < j; i++) {
table += '<tr>';
table += '<td>' + Employees[i].Name + '</td>';
table += '<td>' + Employees[i].EmailAddress + '</td>';
table += '<td>' + Employees[i].Title + '</td>';
table += '<td>' + Employees[i].Expertise + '</td>';
table += '<td>' + Employees[i].PhoneNumber + '</td>';
table += '</tr>';
}
table += '</table>';
$("#pager").append(table);
});
You are using jQuery. Then it should be something like this:
var table=$("<table>",{
id:"employeelist"
}).addClass("table");
table.appendTo($("#pager"));
$("#pager").append(table);
$.each(Employees, function(index, employee){
var row=$("<tr>",{});
$("<td>",{
html:employee.name
}).appendTo(row);
$("<td>",{
html:employee.EmailAddress
}).appendTo(row);
$("<td>",{
html:employee.Title
}).appendTo(row);
$("<td>",{
html:employee.Expertise
}).appendTo(row);
$("<td>",{
html:employee.PhoneNumber
}).appendTo(row);
row.appendTo(table);
});