Call a function passing a file name from dynamically created table - javascript

I am trying to pass a file name from dynamically created table and getting some Uncaught ReferenceError: Q1_58_English_Resume is not defined
at HTMLAnchorElement.onclick (AddRequirement:1)
Here the file name is "Q1_58_English_Resume"
The script for dynamic table is below
if (filesData.length > 0) {
var table = '';
table += '<table class="radar-grid-table" id="TableAttach">';
table += '<thead>';
table += '<tr>';
table += '<th>Files</th>'
//table += '<th>Select</th>';
table += '<th>Actions</th>';
table += '</tr>';
table += '</thead>';
table += '<tbody>';
$.each(filesData, function (i, item) {
table += '<tr>';
table += '<td>' + item + '</td>';
//table += '<td title="' + item.AttachmentId + '">' + item.AttachmentId + '</td>';
//<input value="' + full.QuestionId + '
table += '<td> Download </td>';
table += '</tr>';
});
table += '</tbody>';
table += '</table>';
return table;
}
And the Function is below:
function DownloadAttachment(fileName) {
debugger;
var url = "/RequirementManagement/OpenFile?ids=" + fileName;
window.location.href = url;
}

Try this , should work
var table = '';
table += '<table class="radar-grid-table" id="TableAttach">';
table += '<thead>';
table += '<tr>';
table += '<th>Files</th>'
//table += '<th>Select</th>';
table += '<th>Actions</th>';
table += '</tr>';
table += '</thead>';
table += '<tbody>';
$.each(filesData, function (i, item) {
table += '<tr>';
table += '<td>' + item + '</td>';
//table += '<td title="' + item.AttachmentId + '">' + item.AttachmentId + '</td>';
//<input value="' + full.QuestionId + '
table += '<td> Download </td>';
table += '</tr>';
});
table += '</tbody>';
table += '</table>';
return table;
}

Related

How to loop through a json data from AWS dynamo db using javascript?

Pasting the GET api url on a browser shows me the json data. It looks like this:
{"Count":2,"Items":[{"date":{"S":""},"time":{"S":""},"email":{"S":"test1#email.com"},"name":{"S":""},"phone":{"S":""},"desc":{"S":""}},{"date":{"S":"3/7/21"},"time":{"S":"8:00am - 9:00am"},"email":{"S":"binia#gmu.edu"},"name":{"S":"Bini A"},"phone":{"S":"1234567890"},"desc":{"S":"I like your cut G"}}],"ScannedCount":2}
But When I try to use ajax request to loop through the data, it returns [Object Object]. Please help me figureout this error.
Here is my frontend code:
$.ajax({
url: 'my URL goes here ...',
type: "GET",
success: function (data) {
alert('data fetched!');
var tr = '<tr><th>Full Name</th><th>Phone Number</th><th>Email</th><th>Requested Date</th><th>Requested Time</th><th>Customer Feedback</th></tr>'; // row
// loop through data and display on table
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name + '</td>';
tr += '<td>' + Item.phone + '</td>';
tr += '<td>' + Item.email + '</td>';
tr += '<td>' + Item.date + '</td>';
tr += '<td>' + Item.time + '</td>';
tr += '<td>' + Item.desc + '</td></tr>';
});
$('#createdHoursDb').append(tr); // update table
console.log(tr);
},
error: function () {
alert('fetch request failed!');
}
});
Here is the response on the page:
[Object Object] on each cell of each row.
As you can see, the value of each property is also an object: "name":{"S":""}
So you can write:
...
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name.S + '</td>';
tr += '<td>' + Item.phone.S + '</td>';
tr += '<td>' + Item.email.S + '</td>';
tr += '<td>' + Item.date.S + '</td>';
tr += '<td>' + Item.time.S + '</td>';
tr += '<td>' + Item.desc.S + '</td></tr>';
});
...
You are seeing object because you have an object inside it {"S": ""}. Either you need to convert your data in the required form or you need to use like Item.name.S everywhere.
const data = {"Count":2,"Items":[{"date":{"S":""},"time":{"S":""},"email":{"S":"test1#email.com"},"name":{"S":""},"phone":{"S":""},"desc":{"S":""}},{"date":{"S":"3/7/21"},"time":{"S":"8:00am - 9:00am"},"email":{"S":"binia#gmu.edu"},"name":{"S":"Bini A"},"phone":{"S":"1234567890"},"desc":{"S":"I like your cut G"}}],"ScannedCount":2};
let tr = '<tr><th>Full Name</th><th>Phone Number</th><th>Email</th><th>Requested Date</th><th>Requested Time</th><th>Customer Feedback</th></tr>'; // row
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name.S + '</td>';
tr += '<td>' + Item.phone.S + '</td>';
tr += '<td>' + Item.email.S + '</td>';
tr += '<td>' + Item.date.S + '</td>';
tr += '<td>' + Item.time.S + '</td>';
tr += '<td>' + Item.desc.S + '</td></tr>';
});
$('#createdHoursDb').append(tr); // update table
console.log(tr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="createdHoursDb">
</table>

Appending to tbody not showing data in table

I am trying to append some data to a Datatables tbody. I do recieve the data when I console.log() the data, but the data does not show when I try to append it to my Datatable (The id of my table is 'example' btw). I do not know where to go in terms of debugging this as well.
asyncRequest.then((tracks) => {
var tableData = '';
// rows
for (track in tracks) {
tableData += '<tr>';
tableData += '<td>' + tracks[track]._id + '</td>';
tableData += '<td>' + tracks[track].Position + '</td>';
tableData += '<td>' + tracks[track].Track + '</td>';
tableData += '<td>' + tracks[track].Artist + '</td>';
tableData += '<td>' + tracks[track].Streams + '</td>';
tableData += '<td>' + tracks[track].Url + '</td>';
tableData += '<td>' + tracks[track].Date + '</td>';
tableData += '</tr>';
}
console.log(tableData);
$(document).ready(function () {
var table = $('#example').DataTable();
$(table).find('tbody').append(tableData);
});
});
</script>
tracks: [0 … 99]
0:
_id: "5e8d677a6e5216bc865e084a"
Position: 1
Track: "Dance Monkey"
Artist: "Tones And I"
Streams: 6155025
Url: "https://open.spotify.com/track/1rgnBhdG2JDFTbYkYRZAku"
Date: "1/1/20"
Can u try this one fisrt destroy then append then refresh it
and put your document ready out of request and initialize there
$(document).ready(function () {
var table = $('#example').DataTable();
});
then after u take data appen it destroy it and refresh it
asyncRequest.then((tracks) => {
var tableData = '';
// rows
for (track in tracks) {
tableData += '<tr>';
tableData += '<td>' + tracks[track]._id + '</td>';
tableData += '<td>' + tracks[track].Position + '</td>';
tableData += '<td>' + tracks[track].Track + '</td>';
tableData += '<td>' + tracks[track].Artist + '</td>';
tableData += '<td>' + tracks[track].Streams + '</td>';
tableData += '<td>' + tracks[track].Url + '</td>';
tableData += '<td>' + tracks[track].Date + '</td>';
tableData += '</tr>';
}
console.log(tableData);
$('#example').DataTable().destroy();
$('#example').find('tbody').append(str);
$('#example').DataTable().draw();
});

JS variable not working in AJAX success

Fetched data from database with php and ajax, Everything is ok except note variable is empty.Can somebody find out the issue why note value is not going to display. How can i fix it.
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
var note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}
This is the output
database table
JSON output
{"groupData":{"id":"23","group_name":"Group B"},"results":
[{"id":"2","team_id":"4","team":"Team
B","player":"Deno","result":"14","note":"Lost"},
{"id":"3","team_id":"4","team":"Team
B","player":"Niob","result":"26","note":"Lost"},
{"id":"4","team_id":"4","team":"Team
B","player":"Skion","result":"76","note":"lost"},
{"id":"5","team_id":"5","team":"Team
C","player":"Bela","result":"47","note":"won"},
{"id":"6","team_id":"5","team":"Team
C","player":"yomi","result":"57","note":"won"}]}
You should set note value infront of cats[team].forEach(function(element) {}). Hope to help, my friend :))
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
var note;
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}

jquery how to add image in table TD near specified text

I have a php scripts which shows data from worldoftanks api server. I show this data in table so I would like to add image near every user whos rank is "Recruit".
This is my javascript for table:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "clan_info.php",
success: function(data){
var htmlString = '<table cellpadding="0px" class="menu1"><tr><th>Username</th><th>Rank</th><th>PR</th><th>BTL</th><th>W/B</th><th>E/B</th><th>Days</th></tr>';
var clanData = JSON.parse(data);
i = 0;
for(userID in clanData){
userData = clanData[userID];
var extraClass = '';
if(i < 3) {
extraClass = 'class="rank' + (i+1) + '"';
}
htmlString += '<tr>';
htmlString += '<td '+extraClass+'>' + userData['name'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['role'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['rating'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['battles'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['w_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['xp_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['days'] + '</td>';
htmlString += '</tr>';
i++;
}
htmlString += '</table>';
console.log(htmlString);
$("#wot").html(htmlString);
}
});
});
</script>
AND MY PHP SCRIPT:
<?php
$clanID = "500006494";
$clanApiPage = "https://api.worldoftanks.eu/wgn/clans/info/?application_id=demo&clan_id=$clanID";
$userApiPage = "https://api.worldoftanks.eu/wot/account/info/?application_id=demo&account_id=";
$clanStrongHoldPage = "https://developers.wargaming.net/reference/all/wot/stronghold/info?application_id=demo&clan_id=$clanID";
$getAndDecode = function($url) {
$jsonData = file_get_contents($url);
$dataArray = json_decode($jsonData, true);
return $dataArray;
};
$determineDays = function($date) {
$datediff = time() - $date;
return floor($datediff/(60*60*24));
};
$jsonData = $getAndDecode($clanApiPage) , ($clanStrongHoldPage);
$clanAccounts = array();
foreach($jsonData["data"][$clanID]["members"] as $memberArray) {
$accountID = $memberArray["account_id"];
$clanAccounts[$accountID]['id'] = $memberArray["account_id"];
$clanAccounts[$accountID]['role'] = $memberArray["role_i18n"];
$clanAccounts[$accountID]['name'] = $memberArray["account_name"];
$clanAccounts[$accountID]['days'] = $determineDays($memberArray["joined_at"]);
}
$accountIDs = implode(",", array_keys($clanAccounts));
$apiPage = $userApiPage . $accountIDs;
$userJsonData = $getAndDecode($apiPage);
foreach($userJsonData["data"] as $userID => $dataArray) {
$playerStatistic = $dataArray["statistics"]["all"];
$clanAccounts[$userID]['rating'] = $dataArray["global_rating"];
$clanAccounts[$userID]['battles'] = $playerStatistic["battles"];
$clanAccounts[$userID]['w_p_b'] = $playerStatistic["wins"]/$playerStatistic["battles"] * 100;//wins per battle
$clanAccounts[$userID]['xp_p_b'] = $playerStatistic["battle_avg_xp"]; //experience per battle
}
$w_p_b = array();
foreach ($clanAccounts as $userID => $row) {
$w_p_b[$userID] = $row['w_p_b'];
}
array_multisort($w_p_b, SORT_DESC, $clanAccounts);
die(json_encode($clanAccounts));
?>
my table sample here: http://www.slovenian-army.tk/members.html
I would like to put image near every user like this:
sloa_clan
Depends on what rank is user. If user is Comander he gets comanders icon
If user is Recruit he gets Recruit icon.
Thank you!
I find out how to do this.
by adding this var:
var username = '<img src="images/' + userData['role'] + '.png" height="25" width="25" />' + userData['name'];
and code now looks like:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "clan_info.php",
success: function(data){
var htmlString = '<table cellpadding="0px" class="menu1"><tr><th>Username</th><th>Rank</th><th>PR</th><th>BTL</th><th>W/B</th><th>E/B</th><th>Days</th></tr>';
var clanData = JSON.parse(data);
i = 0;
for(userID in clanData){
userData = clanData[userID];
var extraClass = '';
if(i < 3) {
extraClass = 'class="rank' + (i+1) + '"';
}
var username = '<img src="images/' + userData['role'] + '.png" height="25" width="25" />' + userData['name'];
htmlString += '<tr>';
htmlString += '<td '+extraClass+'>' + username + '</td>';
htmlString += '<td '+extraClass+'>' + userData['role'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['rating'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['battles'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['w_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['xp_p_b'] + '</td>';
htmlString += '<td '+extraClass+'>' + userData['days'] + '</td>';
htmlString += '</tr>';
i++;
}
htmlString += '</table>';
console.log(htmlString);
$("#wot").html(htmlString);
}
});
});
</script>

Convert a JS Array ìnto HTML Table | Weird <tbody> Tag?

When I use this code, all the information is displayed in only one column. Also, if I check with Google Chrome, there are many <tbody> tags that were added to table.innerHTML .
http://puu.sh/4oLmM.png
How can I make it so it displays the header and each content[i] horizontally?
<table id="table1" border=\"5\" cellpadding=\"10\">
<script>
var table = document.getElementById('table1');
table.innerHTML = '';
var header = ['Method','Gp/Exp','Exp/H']
var content = [
['Kill',1,100],
['Die',42,1222],
['Yo',1,1245]
]
//Header
table.innerHTML += '<tr>';
for(var i in header){
table.innerHTML += '<th>' + header[i] + '</th>';
}
table.innerHTML += '</tr>';
//Content
for(var i in content){
table.innerHTML += '<tr>';
for(var j in content[i]){
table.innerHTML += '<td>' + content[i][j] + '</td>';
}
table.innerHTML += '</tr>';
}
</script>
I suspect this is what Ian meant:
var html = '<tr>';
for(var i in header){
html += '<th>' + header[i] + '</th>';
}
html += '</tr>';
for(var i in content){
html += '<tr>';
for(var j in content[i]){
html += '<td>' + content[i][j] + '</td>';
}
html += '</tr>';
}
table.innerHTML = html;
The way you've done it, you're adding badly formed HTML to the element. The overall string is fine, but my guess is that every time you do table.innerHTML +=, it realises that you're creating a dodgy HTML string, and messes around with it to get something that is valid HTML.

Categories