Appending row to html table with javascript - javascript

When my data coming from json and i tried to append row for my datatable with this code. But it didn't work. How can i fix this ?
<table style="width:300px" >
<thead>
<th>
Name
</th>
</thead>
<tbody id="location">
</tbody>
</table>
$.ajax(
{
type: "GET",
url: 'http://jsonplaceholder.typicode.com/users',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var trHTML = '';
for (var i = 1; i > data.length; i++) {
console.log(data[i].name);
trHTML += '<tr><td><span>' + data[i].name + '</span></td></tr>';
};
$('#location tbody').append(trHTML);
},
error: function (msg) {
alert(msg.responseText);
}
});
My actual goal is adding row to footable datatable plugin but i can't fix it too.

There are a few issues with your code. Most are already mentioned in the commennts:
1) Your loop does not work because the condition i > data.length is never true. I suggest using jQuery.each(...) to loop over data. Or fix it to i < data.length but then you also have to start with var i = 0.
2) $('#location tbody') does not exist in your html. That would be a tbody element inside an element with the id location. You want $('tbody#location') or just $('#location') as you should not have multiple items with the same id in your html anyway.
3) Your html inside thead is not correct. It will work this way, but it is not clean html.
Hope this list helps. It basically summarises the comments. (Thanks to all you guys here!)

Related

Push one Row from Table 1 to table 2 and Splice the same row from Table 1 and vice-versa

I have created a Method GetOpPriv() in the Home Controller which retrieves a JSON from a stored procedure.
I have two tables on the Index View id='table1' & 'table2'
I have Displayed the JSON values on 'table1' using JQuery Ajax.
Now, I want to select rows from table1 and send those JSON values to table2 on click of a button.
On click of 1st button, the value should be sent to table2 and the same value should be spliced from table1 and vice versa for the 2nd button.
How can I do the Push and splice at the same time?
Home Controller
public JsonResult GetOpPriv()
{
using (MvcAssignmentEntities db = new MvcAssignmentEntities())
{
var op =( from data in db.OPERATION_PRIVILEGE()
select new
{
OperationName = data.OperationName,
PrivilegeName = data.PrivilegeName
}).ToList();
return Json(op, JsonRequestBehavior.AllowGet);
}
}
JQuery Ajax
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr><td>" + item.PrivilegeName + "</td>" + "<td>" + item.OperationName + "<td>";
});
$("#table1").html(row);
},
error: function (result) {
alert("Error");
}
})
});
</script>
<caption class="display-4">Available Privilege:</caption>
<table class="table-bordered" style="float: left" id="table1">
<thead>
<tr>
<th>Operation </th>
<th>Privilege Name</th>
</tr>
<tbody></tbody>
</table>

How to submit dynamic data without form?

I am getting data as form of Java Bean and I am inserting each value into a table.
Values are retrieved as common way at first.
But I added some Javascript source, so that I can modify the value if I click any area near it.
Now I would like to save the data in database as well if there was any change after I modify.
How can I do that?
Here is my HTML code
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-editable>${engboardVO.word}</td>
<td data-editable>${engboardVO.dialogue}</td>
<td data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
And Javascript
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
/* var $input = $('<input style="width:500px; height:100px"/>').val( $el.text() ); */
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.replaceWith($input);
var save = function() {
var $td = $("<td data-editable />").text($input.val());
$input.replaceWith($td);
};
$($input).blur(function() {
save();
})
});
You can use ajax for submitting data without form.
I can see you are using jQuery library. So I am writing code based on this library.
In HTML:
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-name="word" data-editable>${engboardVO.word}</td>
<td data-name="dialogue" data-editable>${engboardVO.dialogue}</td>
<td data-name="practice" data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
In javascript:
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.html($input);
var field_name = $el.attr('data-name');
var save = function() {
var $val= $input.val();
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
};
$($input).blur(function() {
save();
})
});
Then in server side, you can save fieldvalue as value of fieldname in your database.
Basically what we are doing here is:
Added an attribute data-name in td tag, its value can be related to your field name in table.
Get the name of attribute in javascript using var field_name = $el.attr('data-name');.
Using post request in ajax call passed the field_name and and value of this field to server.
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
Now in server side, you need to fetch this data as you fetch normally for post request in submit of a form and save this data in database.
url is same as action you provide in form tag.
Edit:
Check now. You were replacing the td, whereas you had to replace html inside td.
Don't worry if you don't have a form or can't have it for some reasons
You can still read the inputs of your web page and use them or send them to the server.
See below a simple example:
var inputs = document.getElementsByTagName('input');
var data = []
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
data.push(inputs[index].value)
}
var json = JSON2.stringify(data);
$.ajax({
type: "POST",
url: "your-api-url",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// done code
}
});

Json object doubles on each return

Each time data returns from the PHP file, it seems like the json object are doubled is some way!? When I run the script for the first time I get 5 rows which is the same amount of rows in the table. But the second time, I get the result twice! What have I done wrong in my script?
function readData() {
$.ajax({
url: "read.php",
type: "POST",
dataType: "json",
data: {
input: 1
},
cache: false,
success: function(data) {
var html = "";
for (i = 0; i < data.length; i++) {
html += "<tr><td>" + data[i].text + "</td></tr>";
}
$(".contentList table").append(html);
},
});
}
Try changing
$(".contentList table").append(html);
to
$(".contentList table").html(html);
.append() will just append more results to the end of the content inside the tag, while .html() will completely replace the content.

Generate table in success ajax MVC

I need generate table in success ajax and draw in html. But I dont know how can I fill my table. I try this, but nothing draw.
$.ajax({
url: '/Private/Index',
method: 'POST',
dataType: "json",
data: $(addNewEduForm).serialize() + '&' + $.param(mm),
traditional: true,
success: function (selected) {
$('#your-modal').modal('toggle');
var row = $('<tr>');
for (var i = 0; i < selected.length; i++) {
row.append($('<td>').html(selected[i]));
}
$('#results').append(row);
},
error: function (error) {
}
});
My console.log(selected) :
PICTURE
And my html, where I need draw the table:
<table class="table_blur">
<tr>
<th>Date</th>
<th>Event</th>
<th>First</th>
</tr>
</table>
As result I need :
<th>Date</th><th>Event</th><th>FirstTeam</th>
<DateFromSelected><EventFrom Selected><FirstTeam>
You need that your code looks like that, for example you need show DateofEvent and FirstTeam.
HTML CODE
<table id="results">
<thead>
<tr>
<td>DateofEvent</td>
<td>FirstTeam</td>
</tr>
</thead>
<tboby>
</tbody>
</table>
JS CODE
$.ajax({
url: '/Private/Index',
method: 'POST',
dataType: "json",
data: $(addNewEduForm).serialize() + '&' + $.param(mm),
traditional: true,
success: function (selected) {
$('#your-modal').modal('toggle');
var row = $('<tr>');
for (var i = 0; i < selected.length; i++) {
row.append($('<td>').html(selected[i].DateofEvent));
row.append($('<td>').html(selected[i].FirstTeam));
}
$('#results').append(row);
},
error: function (error) {
}
});
*remember that you return a collection of objects and you access them by name.

Append Ajax results "live" from success function

Question: Why don't elements appended to the DOM from my AJAX success function appear until after the success function has returned?
Context: I am using AJAX to get a JSON object with about 6000 inner objects that I want to use to populate a table. Unfortunately it takes about 10 seconds to create the table, so I'd like to give the user some visual feedback while it loads. I thought the user would be able to see table rows "live" as I call append but they don't load until success returns. When that didn't work, I tried updating the width of a Bootstrap progress bar, but the bar simply freezes during processing.
Goal: I would like the user to either see the table rows as they are appended or a progress bar at updates properly.
Code:
AJAX call:
$.ajax({
type: "GET",
url: myUrl,
contentType: "application/json; charset=UTF-8",
dataType: "json",
success: function(results){
for(var i in results) {
$("#bar").css("width", s / results.length + "%");
console.log(i);
var t_cell = $('<td class="'+attrs[i]+'">');
t_cell.css("background-color", results[i]["val0"]);
t_cell.append($("<span class='val'>").text(results[i]["val1"]));
t_cell.append($("<span class='raw'>").text(results[i]["val2"]]));
t_row.append(t_cell);
$("#review_table > tbody").append(t_row);
}
$('#progress').hide();
}
});
HTML:
<div id="progress" class="progress progress-striped active">
<div id="bar" class="bar" style="width: 1%;"></div>
</div>
<div id='review_div'>
<table class='table table-condensed' id='review_table'>
<thead></thead>
<tbody></tbody>
</table>
</div>
Try
$.ajax({
type : "GET",
url : myUrl,
contentType : "application/json; charset=UTF-8",
dataType : "json",
success : function(results) {
var i = 0;
function process() {
while (i < results.length) {
console.log(results[i])
$("#bar").css("width", s / results.length + "%");
console.log(i);
var t_cell = $('<td class="' + attrs[i] + '">');
t_cell.css("background-color", results[i]["val0"]);
t_cell.append($("<span class='val'>").text(results[i]["val1"]));
t_cell.append($("<span class='raw'>").text(results[i]["val2"]));
t_row.append(t_cell);
$("#review_table > tbody").append(t_row);
i++;
if (i % 25 == 0) {
setTimeout(process, 0);
break;
}
}
}
process();
$('#progress').hide();
}
});
You could try something like this:
for(var i in results) {
createRow(i);
}
and
function createRow(i){
var t_cell = $('<td class="'+attrs[i]+'">');
t_cell.css("background-color", results[i]["val0"]);
t_cell.append($("<span class='val'>").text(results[i]["val1"]));
t_cell.append($("<span class='raw'>").text(results[i]["val2"]]));
t_row.append(t_cell);
$("#review_table > tbody").append(t_row);
}
However, I really don't think you should be rendering 6000 rows in a table though. Try paginating your table using a library. DataTables has a section on how to paginate Bootstrap tables specifically.
http://www.datatables.net/blog/Twitter_Bootstrap
Rather than thinking of it as pagination you could actually write a loop that fetches your records in smaller chunks; maybe try 100 records at a time. As you're appending your 100 records to the DOM, your loop keeps fetching and appending in the background. You would have to be careful to keep them in the order you want them since there is no guarantee data will be returned in the order requested. I would maybe try using .after() to append the data in the right order. With some tinkering I think this could produce a clean and efficient user experience.

Categories