Rest Api: data shows on console but html table shows undefined - html

My post data is being displayed on the console. But the html table shows undefined
The image below shows the problem.
My Jquery Code:
$(document).ready(function(){
//Loading all posts
var loadposts=function(){
$.ajax({
url:"http://localhost:12091/api/post/",
crossdomain: true,
method:"GET",
complete:function(xmlhttp,status){
if(xmlhttp.status==200)
{
var data=xmlhttp.responseJSON;
$("#msg").html(data[0]);
console.log(data[0]);
var str='';
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td><button class='btn btn-danger' onclick=\"deletepost("+data[i].PostId+")\">Delete</button></td>";
str += "<td><button class='btn btn-info' onclick=\"editpost()\">Edit</button></td>";
str += "</tr>";
}
$("#show__posts tbody").html(str);
}
else
{
$("#msg").html(xmlhttp.status+":"+xmlhttp.statusText);
}
}
});
}
loadposts();
});
The html table:
<div class="container">
<p id="msg"></p>
<table class="table table-striped" border="1" id="show__posts" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>User Id</th>
<th>Post Id</th>
<th>Post</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
What am I doing wrong?
Probably irrelevant but i'm using asp.net web api in the backend

JavaScript doesn't have a .length property for objects. If you want to work it out, you have to use Object.keys(data).length instead.

Related

insert only filled rows from table to json array by check each row if it is not empty insert data in array otherwise skip that row

In my scenario i have a table which inputs data from user and save the table rows first in json array then pass this array to MVC controller using ajax.
The data in table (eg name eid student id )are fill from server side from controller using jquery then user have to provide marks against each student.then the table data along with marks pass from view to controller using ajax.
Scenario for Problem:
if user fill some rows not all ones then only filled rows data should be inserted in json array.How can I achieve this using Jquery . first check if the row is filled then add that row data in array
#Html.DropDownList("ClarderSousSecteurID", "--- Tous ---")
<input id="date" value='#DateTime.Now.ToString(" dd/mm/yyyy")' />
<input id="date" type="hidden" value='#ViewBag.P_No' />
<table id="tableId" class="table table-bordered table-condensed table-hover table-striped">
<thead>
<tr>
<th>Student_id</th>
<th>Name</th>
<th>Did he perform well</th>
<th>According to Criteria</th>
<th>To the point</th>
<th>EID</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input type="submit" id="savebtn" class="btn btn-success" value="Save" style="display:none;" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
var date;
var val;
$("#ClarderSousSecteurID").change(function () {
val = $("#ClarderSousSecteurID").val();
$("#tableId > tbody").empty();
date = $("#date").val();
$("#savebtn").show();
alert("selected=" + val + date)
var data = JSON.stringify({
'val': val
});
$.ajax({
type: "POST",
url: "/judge_dashboard/Getstudents",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var tr;
//Append each row to html table
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].stud_id + "</td>");
tr.append("<td>" + data[i].stud_name + "</td>");
tr.append("<td><input id='one'></td>");
tr.append("<td><input id='two'></td>");
tr.append("<td><input id='three'></td>");
tr.append("<td>" + data[i].E_id + "</td>");
$('table').append(tr);
}
alert(r + "=== record(s) inserted." + data);
}
});
});
$("body").on("click", "#savebtn", function () {
var marks = new Array();
$("#tableId TBODY TR").each(function () {
{
alert("filled row")
var row = $(this);
var details = {};
details.DATE = date;
details.One_marks = row.find("TD").eq(2).html();
details.Two_marks = row.find("TD").eq(3).html();
details.Three_marks = row.find("TD").eq(4).html();
details.Eid = row.find("TD").eq(5).html();
details.Contest_id = val;
marks.push(details);
}
});
//Send the JSON array to Controller using AJAX.\
var data = JSON.stringify({
'judges': marks,
'val': val
});
alert(data);
$.ajax({
type: "POST",
url: "/Contest_judge/InsertJudge",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + "=== record(s) inserted." + data);
}
});
});
</script>
Note: order of data in Json Array should be following
Date,one(or One_marks),two(or Two_marks),three(or Three_marks),Eid
because I have to insert the whole row as a object in database from controller so the order of column elements for each row in json array matter
Based on your sample, I wasn't sure if you were labeling your inputs, so this example has no-name inputs, but inherits their context from the header row.
$("body").on("click", "#savebtn", function() {
var marks = new Array();
$("#tableId tbody tr").each(function() {
let mark = {
Eid: $(this).find('td').eq(5).text(),
DATE: 'date',
Contest_id: 'val'
}
let empty = true;
$(this).find('td').each(function(i, o) {
if ($(o).find('input').length > 0 && $(o).find('input').eq(0).val().trim() !== '') {
mark[$("#tableId thead th").eq(i).text()] = $(o).find('input').eq(0).val();
empty = false;
}
})
if (!empty) marks.push(mark);
});
//Send the JSON array to Controller using AJAX.\
var data = JSON.stringify({
'judges': marks,
'val': 'val'
});
console.log(data)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableId" class="table table-bordered table-condensed table-hover table-striped">
<thead>
<tr>
<th>Student_id</th>
<th>Name</th>
<th>Did he perform well</th>
<th>According to Criteria</th>
<th>To the point</th>
<th>EID</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>abc</td>
<td><input/></td>
<td><input /></td>
<td><input /></td>
<td>111</td>
</tr>
<tr>
<td>223</td>
<td>abc</td>
<td><input /></td>
<td><input /></td>
<td><input /></td>
<td>222</td>
</tr>
<tr>
<td>323</td>
<td>abc</td>
<td><input /></td>
<td><input /></td>
<td><input /></td>
<td>333</td>
</tr>
</tbody>
</table>
<button id='savebtn'>save</button>

How to select Html table row using jquery

I am using html table. which is creating dynamically and want to select Table row if we clicked on selected row how it can be possible using jQuery. I am binding that table using AJAX call on success event.
I am getting alert message but for different row selection result will remains same. (Only first row value are displaying for every row click) ?
where i am doing mistake kindly help me
I tried Like this:
$(document).ready(function () {
$("#test").click(function () {
$('.selected').removeClass('selected');
$(this).addClass("selected");
var product = $('.p', this).html();
var infRate = $('.i', this).html();
var note = $('.n', this).html();
alert(product + ',' + infRate + ',' + note);
});
});
BINDING TABLE
function OnSuccessFunctionalGridCall(data, status) {
//d = data.GetDraftedSDDResult.ResultObject;
d = AllDataGrid;
var tbl = "<table id='lineItemTable' border='1' cellspacing='0' cellpadding='3' width='100%'>";
if ($('#tdDraftSDD').length != 0) // remove table if it exists
{ $('#tdDraftSDD').empty(); }
if (d.length == 0) {
alert('No Record to display');
}
else {
tbl += " <tr class='tr-Highlighted' style='height:30px;'><td class='align-text-center' >Sr.No</td><td class='align-text-center' style='font-weight:bold !important'>User Login</td><td class='align-text-center' style='font-weight:bold !important'>User Name</td><td class='align-text-center' style='font-weight:bold !important'>Status</td></tr>";
for (i = 0; i < d.length; i++) {
tbl += "<tr><td function='draftlineNumber' class='width4p align-text-center'>"
+ (i + 1) + "</td><td function='draftlineNumber' class='width6p'>"
+ d[i].USER_LOGIN + "</td><td class='p'>"
+ d[i].USER_NAME + "</td><td class='i'>"
+ d[i].Status; + "</td><td class='n'></tr>"
}
tbl += "</table>";
$("#tdDraftSDD").append(tbl);
return;
}
}
HTML TABLE
<tr id="trGridView">
<td>
<table border="0" cellspacing="3" cellpadding="3" class="width100p">
<tr>
<td>
<div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabs">
<table id="tblDraftedSDD" class="contentTable">
<tr id="displaytable">
<td>
<table id="test" class="ui-corner-all contentTable">
<tr>
<td id="tdDraftSDD" class="width100p borderTable table_new"></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
How to selected particular row can any one help me on same ?

How to put elements of an array into html table rows and columns

I need to put each element of an array into the corresponding table column, but currently it just puts the entire array into the first column. I feel like this solution will be a simple nested for loop but I am unsure, would appreciate any help. Thanks!
index.html
<div id="PersonContainer" class="DBcontainer">
<form action='/addPerson' method="GET"></form>
<table class="center" id="personTable">
<caption>People Table</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Hooks ID</th>
<th>Soft Plastic ID</th>
<th>Rods ID</th>
<th>Number of Hooks</th>
<th>Number of Soft Plastics</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="displayPerson()">Click Me</button>
</form>
</div>
index.html script
<script>
function displayPerson() {
// console.log('test');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var person = xhttp.responseText;
var element = document.getElementById("personTable");
var result = JSON.parse(person).map((item) => Object.values(item));
for(i = 0; i < result.length; i++){
element.innerHTML += '<td>' + result[i] + '</td>';
}
}
};
xhttp.open("GET", "/AddPerson", true);
xhttp.send();
}
</script>
the xhttp.responseText
[{"id":1,"first_name":"Tyler","last_name":"Marlow","hooks_id":1,"sp_id":1,"rods_id":1,"num_hooks":10,"num_sp":30},{"id":2,"first_name":"Jon","last_name":"Marlow","hooks_id":2,"sp_id":1,"rods_id":1,"num_hooks":50,"num_sp":200}]
Also note that when another person is added I would like another row to be added to the table with the values in proper columns
Putting a new row onto a table in JavaScript can be done with the insertRow function and adding a cell to a row can be done with the insertCell function.
So in your code (depending on exactly what your parsed JSON looks like) in your for loop you are going to do something like:
row = element.insertRow(i); // add a new row to your table
row.insertCell(0).innerHTML =
row.insertCell(1).innerHTML =
and so on
....
But of course you'd put the insertCell line into a for loop as well.
function displayPerson() {
// console.log('test');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var person = xhttp.responseText;
var element = document.getElementById("personTable");
var rows = ``;
JSON.parse(person).forEach(item => {
var row = `<tr>`;
row += `<td>${item.first_name}</td>`;
row += `<td>${item.last_name}</td>`;
row += `<td>${item.hooks_id}</td>`;
row += `<td>${item.sp_id}</td>`;
row += `<td>${item.rods_id}</td>`;
row += `<td>${item.num_hooks}</td>`;
row += `<td>${item.num_sp}</td>`;
row += `</tr>`;
rows += row;
});
element.innerHTML = rows;
}
};
xhttp.open("GET", "/AddPerson", true);
xhttp.send();
}
<div id="PersonContainer" class="DBcontainer">
<form action='/addPerson' method="GET">
<table class="center">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Hooks ID</th>
<th>Soft Plastic ID</th>
<th>Rods ID</th>
<th>Number of Hooks</th>
<th>Number of Soft Plastics</th>
</tr>
<thead>
<tbody id="personTable">
</tbody>
</table>
<button type="button" onclick="displayPerson()">Click Me</button>
</form>
</div>

Applying Bootstrap table-striped to dynamic table not working

Creating a dynamic table where pageList has variable length with each response. Attempting to apply Bootstrap's table-striped class however this styling seems to not work. Any thoughts? I've looked at other examples but they don't seem to match what is going on here :
<div class="container-fluid">
<div class="table-responsive">
<table class="table table-outline table-striped table-hover">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
</thead>
<tbody style="background-color: white; ">
<tr>
<td class="name"></td>
<td class="address"></td>
<td class="email"></td>
</tr>
</tbody>
</table>
</div>
</div>
/////
for (r = 0; r < pageList.length; r++) {
$('.name').append("<br>" + fullName + "<br>");
$('.address').append("<br>" + homeAddress + "<br>");
$('.email').append("<br>" + "$" + personalEmail + "<br>");
}
So there appear to be a few issues with your example code.
The main issue is that your for loop does not add any rows to the table. Each iteration through the loop should add a <tr>, a child <td> and the data in the table cell.
The background-color: white; is unnecessary
Your for loop is iterating over pageList. However, it does not appear to actually assign the next element in the pageList to a variable. Presumably each element is an object containing an object with fields for fullName, homeAddress and personalEmail.
Based on this assumption, you can use code similar to the example below to create a dynamic table.
var pageList = [{
fullName: "John Doe",
homeAddress: "13 Home St",
personalEmail: "you#mail.com"
},
{
fullName: "Jane Doe",
homeAddress: "55 Work St",
personalEmail: "me#mail.com"
}
];
for (r = 0; r < pageList.length; r++) {
var e = pageList[r];
var tbody = $("#theTable tbody");
tbody.append("<tr><td>" + e.fullName + "</td><td>" + e.homeAddress + "</td><td>" + e.personalEmail + "</td></tr>");
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
<div class="table-responsive">
<table id="theTable" class="table table-outline table-striped table-hover">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
In your example, you're only appending the new values to the existing row in the table. Instead, you should insert a new row for each item.
Something like:
var pageList = [
{
fullName: 'TestName1',
homeAddress: 'TestAddress1',
personalEmail: 'TestEmail1'
},
{
fullName: 'TestName2',
homeAddress: 'TestAddress2',
personalEmail: 'TestEmail2'
}
];
var table = document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0];
for(const item of pageList) {
var row = table.insertRow(0);
var nameCell = row.insertCell(0);
var addressCell = row.insertCell(1);
var emailCell = row.insertCell(2);
nameCell.className = 'name';
addressCell.className = 'address';
emailCell.className = 'email';
nameCell.innerText = item.fullName;
addressCell.innerText = item.homeAddress;
emailCell.innerText = item.personalEmail;
}

Insert an HTML table into sharepoint 2013 webpart script

I have a problem, I've created a simple webpart that perfoms basics CRUD OPERATIONS, I wanted to add an HTML table to format and display the results retrieved from the READ operation, here is the code for a better understanding:
function retriveListItem() {
execute(
"items?$orderby=Nom&$select=Nom,Cognom,Indirizz",
"GET",
"GET",
null,
function (data, status, xhr) {
$("#result").empty();
var string = "<table><tr><th>Nome</th><th>Cognome</th><th>Indirizzo</th></tr>";
$("#result").append(string);
string = string = "";
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
string = "<tr><td>" + item.Nom + "</td><td>" + item.Cognom + "</td><td>" + item.Indirizz + "</td></tr>";
$("#result").append(string);
}
string = "</table>";
$("#result").append(string);
},
function (xhr, status, error) {
$("#result").empty().text(error);
});
}
But when the page is rendered in the browser if I hit the F12 key I discover that sharepoint automatically adds the tbody tag (which I haven't wrote) and it close the tag /table automatically in the wrong position here is the code rendered in the browser:
<div id="result">
<table>
<tbody>
<tr>
<th>Nome</th>
<th>Cognome</th>
<th>Indirizzo</th>
</tr>
</tbody>
</table>
<tr>
<td>Giova</td>
<td>Nardi</td>
<td>Viale della Cagna, Verona</td>
</tr>
<tr>
<td>Antonio</td>
<td>Petrarca</td>
<td>Via Camello 31, Rovegna</td>
</tr>
<tr>
<td>Luca</td>
<td>Mandelli</td>
<td>Via Rossini, 32 Cesano Maderno</td>
</tr>
</div>
Does anybody knows why that? Any idea on how to workaround that issue? Thanks a lot
It looks like in your code, your string variable is just overwriting itself, and you are posting the results to the browser each time. Rather than using .append() each time you update the string, just use a string += .... and then append after the loops have run and the string is populated with the full table.
Here is a JSFiddle as an example using your code (for the most part).
So your code would look like:
function retriveListItem() {
execute(
"items?$orderby=Nom&$select=Nom,Cognom,Indirizz",
"GET",
"GET",
null,
function (data, status, xhr) {
$("#result").empty();
var string = "<table><tr><th>Nome</th><th>Cognome</th><th>Indirizzo</th></tr>";
//$("#result").append(string);
//string = string = "";
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
string += "<tr><td>" + item.Nom + "</td><td>" + item.Cognom + "</td><td>" + item.Indirizz + "</td></tr>";
//$("#result").append(string);
}
string += "</table>";
$("#result").append(string);
},
function (xhr, status, error) {
$("#result").empty().text(error);
});
}
Hope this helps!
You can always insert HTML into an existing table using JQuery's after() method. Since you have a first <tr> already, you can poke in your built up HTML after that first row:
// First, put your basic table into #result
$("#result").html('<table id="resulttable"><tr><td>...</td></tr></table>');
// Next build up the necessary rows and columns
for (var i = 0; i < data.d.results.length; i++) {
// Build up your string as above
}
// Next, poke it into the DOM after the first <tr>
$("#resulttable tr").first().after(string);
You will find a full mockup below. The results data and the code to populate rows is shown in the page's <head> section. Below that, in the <body> a table is defined with ID mytab. That ID is picked up in the code that populates the rows.
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
data = { d : {
results: [
{ Nom: 'nom1', Cognom: 'Cognom1', Indirizz: 'Indirrizz1' },
{ Nom: 'nom2', Cognom: 'Cognom2', Indirizz: 'Indirrizz2' },
{ Nom: 'nom3', Cognom: 'Cognom3', Indirizz: 'Indirrizz3' } ] } };
$(document).ready(function() {
for (var i = 0; i < data.d.results.length; i++) {
item = data.d.results[i]
str = '<tr><td>' + item.Nom + '</td><td> ' + item.Cognom +
'</td><td>' + item.Indirizz + '</td></tr>';
$('#mytab tr').first().after(str);
}
});
</script>
</head>
<body>
<table id="mytab">
<tr>
<td>First column</td> <td>Second column</td> <td>Third column</td>
</tr>
</table>
</body>
</html>