Data showing undefined in table - javascript

I am trying to get my data into an HTML table. The JavaScript is properly detecting the data and is showing two rows in the table, which is correct. The issue is each of the fields of both rows display undefined. Not sure where to go from here.
$(function() {
var records = [];
$.getJSON('https://v1.nocodeapi.com/devmarq/airtable/RiBnzHulmTPHkgnD?tableName=JobListings&fields=company,logo,companyDescription,role,roleDescription,location,link,dateAdded&view=AllListings', function(data) {
$.each(data.records, function parseJSON(i, f) {
var tblRow = "<tr>" + "<td>" + f.company + "</td>" + "<td>" + f.companyDescription + "</td>" + "<td>" + f.role + "</td>" + "<td>" + f.roleDescription + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="wrapper">
<div class="profile">
<table id="userdata" border="2">
<thead>
<th>Company</th>
<th>Company Description</th>
<th>Role</th>
<th>Role Description</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
Again the table is showing two rows, which is correct, but each value of the rows says undefined.

You need to pull the fields key out of the record object:
$(function() {
var records = [];
$.getJSON('https://v1.nocodeapi.com/devmarq/airtable/RiBnzHulmTPHkgnD?tableName=JobListings&fields=company,logo,companyDescription,role,roleDescription,location,link,dateAdded&view=AllListings', function(data) {
$.each(data.records, function parseJSON(i, { fields: f }) {
var tblRow = "<tr>" + "<td>" + f.company + "</td>" + "<td>" + f.companyDescription + "</td>" + "<td>" + f.role + "</td>" + "<td>" + f.roleDescription + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="wrapper">
<div class="profile">
<table id="userdata" border="2">
<thead>
<th>Company</th>
<th>Company Description</th>
<th>Role</th>
<th>Role Description</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
I changed the second argument of the parseJSON function from f to { fields: f }; this uses object destructuring to grab the value of the fields entry in the object passed to the second argument and assigns it to the f variable so that the rest of the code can use that object to get their values.

Related

How to append row(with mutiple input column and one dropdownlistcolumn) to table on ajax sucess

I need to add drop down or list box in place of comment from model added at view. kindly suggest any other alternative method since i am new to this
Html code:
#model Sampleapplication.Models.samplemodel
<body>
<table id="tabledetails" class="table table-bordered loaded-table">
<thead>
<tr>
<th> <p>Id</p></th>
<th> <p>Name</p></th>
<th> <p>Department</p></th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
on ajax success:
success: function (data) {
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='prtoducttd1'>" + item.Id + "</td>"
+ "<td class='prtoducttd2'>" + item.Name + "</td>"
+ "<td class='prtoducttd11'>#Html.ListBoxFor(m => m.sDepartmentList, Model.lstToDepartment, new { Name = "Departmentlst", id = "Departmentlst", #placeholder = "Select Deaprtment" })</td>"
+ "</tr>";
$('#tabledetails tbody').append(rows);

Not getting onclick event to fire from programmatically built table

I have a table that is programmatically added with an onclick event that calls a specific javascript function with the id of the row I want to edit. However it is not called. I have tried changing the button by adding a class and trying to get something there but it does not work. This used to work and I cannot figure out why or how to fix it.
function buildTable() {
$.ajax({
url: "getTable.php",
dataType: "json",
success: function(result) {
if (result != null) {
$('#measurements tbody tr').remove();
result.forEach(function (measurement) {
var message = "<tr><td>" + dateFromtimestamp(measurement.weigh_date) + "</td>";;
message += "<td>" + measurement.weight + "</td>";
message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
message += "<td>" + measurement.upperBp + "</td>";
message += "<td>" + measurement.lowerBp + "</td>";
message += "<td>" + measurement.comment + "</td>";
message += "<td><button type='button' class='btn btn-outline-warning' onlick='editRow(" + measurement.id + ")'>";
message += "<span class='glyphicon glyphicon-pencil'></span></button> ";
message += "<button type='button' class='btn btn-outline-danger' onlick='removeRow(" + measurement.id + ")'>";
message += "<span class='glyphicon glyphicon-remove'></span></button></td></tr>";
$('#measurements').append(message);
});
}
}
});
}
The following is the HTML table it is being added to:
<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
<table class="table table-striped" id="measurements">
<thead class="thead-dark">
<th scope="col">Date</th>
<th scope="col">Weight</th>
<th scope="col">Waist</th>
<th scope="col">Systolic (Upper)</th>
<th scope="col">Diastolic (Lower)</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</thead>
<tbody>
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
This is the edit function in question just in case I miss something with the argument signature:
function editRow(id) {
$.ajax({
url: "getMeasurement.php",
type: "post",
dataType: "json",
data: {
"id": id
},
success: function(data) {
if (data != null) {
data.forEach(function(result){
var id = result.id;
$('#editMeasurement').modal('show');
$('#editupper').val(result.upperBp);
$('#editlower').val(result.lowerBp);
$('#editwaist').val(result.waist);
$('#editweight').val(result.weight);
$('#editcomment').text(result.comment);
$('#editRowHidden').val(id);
});
}
}
});
}
I have tried changing the button by adding a class:
and trying to catch the event with $('.editRow').on("click", function() {} event with the same results.
You have a typo onlick instead of onclick.
Also, you could consider to use passive event listener as:
$(document).on("click", <target>,<your function>});
where <target> is the jquery selector for you button
and <your function> your callback.
This would increase readability and as well helps to keep the separation between HTML and JS. And also work for dynamically inserted targets.
Thanks to kmgt. If it was a snake it would have bit me. Have to use 'onclick' instead of 'onlick'.
First of all I agree with #dmitrii-g that you should use event-delegation to be able to handle any events on elements, that were added after DOM was rendered. (added dynamically). After that you should try to debug/print to console any information needed to ensure that you are passing correct values into your function. I've prepared sample example which will demonstrate this approach:
const result = [{
weigh_date: '01/01/2019',
weight: '200lbs',
id: 1,
waist: 'waist',
upperBp: 'upperBp',
lowerBp: 'lowerBp',
comment: 'comment'
},
{
weigh_date: '01/01/2015',
weight: '100lbs',
id: 2,
waist: 'waist',
upperBp: 'upperBp',
lowerBp: 'lowerBp',
comment: 'comment'
}
];
function buildTable() {
if (result != null) {
$('#measurements tbody tr').remove();
result.forEach(function(measurement) {
var message = "<tr><td>" + measurement.weigh_date + "</td>";
message += "<td>" + measurement.weight + "</td>";
message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
message += "<td>" + measurement.upperBp + "</td>";
message += "<td>" + measurement.lowerBp + "</td>";
message += "<td>" + measurement.comment + "</td>";
message += "<td><button type='button' class='btn btn-edit btn-outline-warning' id='" + measurement.id + "'>Edit</button> ";
message += "<button type='button' class='btn btn-delete btn-outline-danger' id='" + measurement.id + "'>Remove</button></td></tr>";
$('#measurements').append(message);
});
}
}
$('#measurements').on('click', '.btn-edit', function() {
const id = $(this).attr('id');
console.log('ID to be edited: ' + id);
// your stuff here
});
$('#measurements').on('click', '.btn-delete', function() {
const id = $(this).attr('id');
console.log('ID to be deleted: ' + id);
// your stuff here
});
buildTable();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
<table class="table table-striped" id="measurements">
<thead class="thead-dark">
<th scope="col">Date</th>
<th scope="col">Weight</th>
<th scope="col">Waist</th>
<th scope="col">Systolic (Upper)</th>
<th scope="col">Diastolic (Lower)</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</thead>
<tbody>
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
try this
$(document).on("click","tr",function() {
console.log(this,"click");
});

show json different field in html table

my code showing the image and title and summary for all json file entries all what i need to show the image , title and summary to the first entry only and will show title to other entries.
please advise.
<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://localhost:8080/Newfolder/test.json";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.image + "</td>" + "<td>" + f.title + "</td>" + "<td>" + f.summary + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "entrydata" border="1">
<thead>
<th>ID</th>
<th>UserName</th>
<th>Message</th>
<th>Location</th>
<th>Time</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
Hard to understand what you're asking but I take it as you want First Name in the first table cell and first name and ID in the second.
var cutName = f.user.username.indexOf( ' ' ),
firstName = f.user.username.substr( 0, cutName == -1 ? 0 : cutName ),
tblRow = "<tr><td>" + firstName + "</td><td>" + firstName + " " + f.id + "</td><td>" + f.message + "</td><td> " + f.location + "</td><td>" + f.at + "</td></tr>";
Basically, use indexOf( ' ' ) to find the space after the first name. If the user only has one name (no space) then it returns -1 otherwise it is the index of the space. Then use substr to cut out the name.
Hope this helps. :)

How to edit table html?

I am building a page with a table, with the ability to add, edit, and delete. I have the add and delete functionality working but not the edit or save. Can anyone tell what is wrong with these functions?
Whenever I click on the edit button it will delete the row (Select check box it will either delete or edit).
Here is my code:
<table id="packageTable">
<thead>
<tr>
<th>Select</th>
<th>Make</th>
<th>Model</th>
<th>SKU#</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
rowNew = 1;
removeRow = -1;
function tableColumn(){
row = rowNew;
if (removeRow >0){
editList();
}else{
var make = $("#make").val();
var modal = $("#model").val();
var sNumber = $("#sNumber").val();
var mPrice = $("#mPrice").val();
var newCol = "<tr id = 'newCol" + row +"'>" +
"<td><input type = 'checkbox'>"+ "</td>" +
"<td id\"mChoice" + row + "\">"+ make + "</td>" +
"<td id\"m0Choice" + row + "\">" + modal +"</td>" +
"<td id\"skChoice" + row +"\">" + sNumber +"</td>"+
"<td id\"prChoice" + row +"\">" + mPrice +"</td>" +
"<td><button onclick ='eRow(" + row + ")'>Edit</button>" +
"<td><button onclick ='delete(" + row + ")'>Delete</button>" +
"</tr>";
$("#packageTable").append(newCol);
rowNew++;
$("#make").val("");
$("#model").val("");
$("#sNumber").val("");
$("#mPrice").val("");
}
}
function eRow(row) {
$("#make").val($('#mChoice'+row).html());
$("#model").val($('#m0Choice'+row).html());
$("#sNumber").val($('#skChoice'+row).html());
$("#mPrice").val($('#prChoice'+row).html());
remove = row;
}
function editsSave(){
$('"#mChoice' + removeRow).html($('#make').val());
$('"#m0Choice' + removeRow).html($('#model').val());
$('"#sNumber1' + removeRow).html($('#sNumber').val());
$('"#mPrice' + removeRow).html($('#mPrice').val());
remove = -1;
}

Getting data from a .json URL and displaying it in HTML with Javascript/JQuery

I am trying to get json data from:
http://api.dailymile.com/entries.json
Then I wish to display this data in a table. The below code works when the json link points to a file already on my computer, but not when referring to a URL.
<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://api.dailymile.com/entries.json";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.id + "</td>" + "<td>" + f.user.username + "</td>" + "<td>" + f.message + "</td>" + "<td> " + f.location + "</td>" + "<td>" + f.at + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "entrydata" border="1">
<thead>
<th>ID</th>
<th>UserName</th>
<th>Message</th>
<th>Location</th>
<th>Time</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
Any help as to why it won't load the json data is appreciated.
As aldux suggests, a simple way of accessing JSON cross-domain is to use JSONP. In your case, the server (dailymile.com) does support JSONP, so you can simply add a ?callback=? parameter to your url, i.e.
var dmJSON = "http://api.dailymile.com/entries.json?callback=?";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.id + "</td>" + "<td>" + f.user.username + "</td>" + "<td>" + f.message + "</td>" + "<td> " + f.location + "</td>" + "<td>" + f.at + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
This is because the AJAX Same Origin Policy tha won't allow you to fetch data from different domains:
http://en.wikipedia.org/wiki/Same_origin_policy
Try this instead:
http://en.wikipedia.org/wiki/JSONP

Categories