How to dynamically create a table using JSON data with jQuery - javascript

I have JSON data which i need to displayed in a table and then apply datatable on that table. Some part of the table is static while others must be created dynamically. There will be dynamic headers and offcource the data data to be shown will be taken from JSON. My Static HTML Code is as follows
<table border="1" align="center" id="info-table">
<thead>
<tr>
<th>Roll No</th>
<th>Student Name</th>
<th>Student ID</th>
<th>Class</th>
Now i have to dynamically add more headers so for that i am using $.each. After that i need to add The TD's to show the data. The code is as follows
obj = $.parseJSON(json.responseText);
if (obj.collection.response.error) {
displayError(obj.collection.response.error);
} else {
//Prepare fields for Attendance codes
$.each(obj.collection.response.attendanceCodes, function(key, value){
$('#info-table tr').append("<th>"+value.title+"</th>");
});
//Add the static headers
$('#info-table tr').append("<th>Teacher Comment</th><th>Admin Comment</th></tr></thead><tbody>");
//Prepare fields for EachStudent
$.each(obj.collection.response, function(i, val){
if(i != 'attendanceCodes'){
$('#info-table').append("<tr><td>"+val.rollNo+"</td><td>"+val.studentName+"</td><td>"+val.studentId+"</td><td>"+val.className+"</td><td align=\"center\"><div class=\"radio-green\"><input type=\"radio\" checked=\"checked\" name=\"attend-"+val.studentId+"\" /></div></td><td align=\"center\"><div class=\"radio-red\"><input type=\"radio\" name=\"attend-"+val.studentId+"\" /></div></td><td><input type=\"text\" style=\"width:200px;\" name=\"teacher-comment-"+val.studentId+"\" /></td><td>- - -</td><td></td><td></td><td></td><td></td></tr>");
}
});
//$('#info-table').dataTable();
}
},
dataType:"JSON"
But this code is not working and i am getting error in console that says:
Uncaught TypeError: Cannot read property 'childNodes' of null

It will be better if you use any jquery plugin for that.Like datatable or jqgrid.It will give good support to JSON and XML based data.
http://trirand.com/blog/jqgrid/jqgrid.html

Yes i got the answer...
We will have to remove the closing tr and thead and the new code for that area will be and it worked.
//Add the static headers
$('#info-table tr').append("<th>Teacher Comment</th><th>Admin Comment</th>");

Related

sending html data to view and then sending to controller to update sql database

I have a HTML table where one of the columns value is dynamically added. I have an update button, upon clicking it I want this data to get updated in my sql database. For this, I am planning to first fetch the table data and put into view , then send data to controller and then updating sql.
I am stuck at the first step,
Descibing table below
<thead>
<tr>
<th>ID</th>
<th >Name</th>
<th>Active</th>
<th>Order By</th>
</tr>
</thead>
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td >#item.AutoID</td>
<td #item.Text</td>
<td >#item.Active</td>
<td>#item.OrderBy</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<input type="submit" value="Update Preference" class="BtnUpdOrderId" />
</div>
I tried this below js function to fetch the data
$(".BtnUpdOrderId").click(function () {
var tr = $(this).closest('tr');
var id = tr.find('input[name="autoid"]').val();
var text = tr.find('input[name="text"]').val();
var active = tr.find('input[name="active"]').val();
var orderby = tr.find('input[name="orderby"]').val();
alert('type1 : ' + id + ' ' + text + ' ' + active + ' ' + active);
});
but not sure why nothing came in alert
var TableData = new Array();
$('#tblLookup1 tr').each(function (row, tr) {
TableData = TableData + $(tr).find('td:eq(0)').text();
alert(TableData);
});
then tried the above block of code to get data in a variable but still not able to get anything.
Once I get the data I can try sending from view->controller.
So need the following help:
what mistake am I making?
once this is fixed, how to send data to sql? (this is a ado.net based mvc project)
you might want to consider creating a json object:
Creating json object in mvc and returning from controller
then build your table Convert JSON array to an HTML table in jQuery
finally, the update need only post back the json object
https://dontpaniclabs.com/blog/post/2013/02/27/posting-json-data-to-an-mvc-controller-via-ajax/
if you going to use this jason object make sure you use serialization
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0
your have to patch these concepts together but there are a lots of tutorials and examples online so it be a good learning experience
I hope this helps
helpful links:
https://www.sqlshack.com/modifying-json-data-using-json_modify-in-sql-server/
Updating a JSON object using Javascript
https://www.geeksforgeeks.org/how-to-convert-json-data-to-a-html-table-using-javascript-jquery/
create json object from html table using selected colums using jquery

jQuery Datatables Reload

I'm facing an issue using the Datatables plug-in regarding a table reload after the user adds a row.
I'm receiving some JSON data as part of a webservice call, after successfully receiving that data, I am calling a function that will build the table rows and append them to the tbody of the datatable as follows:
const buildTableRows = obj => {
const table = document.querySelector('#participantes tbody');
table.innerHTML = "";
for (item of obj) {
const tableRow = `<tr id="${item.ContactoId}" data-contributos="${item.Contributos}" data-updated="false" class="participante-row"><td><i class="material-icons">arrow_right</i>${item.Nome}</td><td class="contributos"><input value="${item.Contributos}">&nbsp&nbsp&nbsp<i class="material-icons delete">delete_forever</i></td></tr>`;
table.insertAdjacentHTML('beforeend', tableRow);
}
}
After this, I call another function responsible for initializing the Datatable and saving it to a global object for future reference:
const buildDataTable = () => {
const table = $('#participantes').DataTable({
"pagingType": "simple_numbers",
"pageLength": 4,
"lengthChange": false,
"columnDefs": [{
"targets": 1,
"orderable": false
}],
responsive: true
});
controlObj.datatable = table;
}
In my HTML I have a dynamically generated select element which lets the user add a row to the table. When the user adds the row, those two functions get called again. I can see the new row in my data structure but the table doesn't get refreshed without a page reload. I went through the plugin docs and tried to use the destroy method, rows.add(), clear(), draw() etc.. but nothing seems to work for me. The table structure is already in the DOM, I just need to reload the table. Any help would be much appreciated
Datatable cannot be clear and redraw for updated HTML DOM for table but it has to be inserted using JSON array.
To refresh it after change in DOM, you need to destroy the table and re-initalize it.
See below example where on click of ADD button I have added new row and reiniitalized the table but before that I have destroyed it.
$(document).ready(function() {
//Initialize the table and save it in a variable.
var table = $('#example').DataTable();
var id = 0;
$('#add').on('click', function(){
table.destroy();
//add row to the table
var html = '<tr><td>' + id + '</td><td>First Name' + id + '</td><td>Last Name' + id + '</td></tr>';
//console.log(html);
$('#example tbody').append(html);
id++;
table = $('#example').DataTable();
});
} );
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.jqueryui.min.css">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="example" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr>
<td>00</td>
<td>First</td>
<td>Last</td>
</tr>
</tbody>
</table>
Click Button to Add row : <input id="add" value=" ADD " type="button">
Yes you can use DataTable api. without destroying table you just need a function.
$(document).ready(function() {
var dt = $('#example').DataTable();
$('#addRow').click(function () {
var rowHtml = $("#newRow").find("tr")[0].outerHTML
console.log(rowHtml);
dt.row.add($(rowHtml)).draw();
});
});
here is working example

How to get value from html select tag option value using onChange event using jQuery data table?

I am working on jQuery Data table to load few data from mysql database.
Here is the html code :
<table id="employee-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>#</th>
<th>User Id</th>
<th>Address</th>
<th>Package Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
From php page I'm loading the data like bellow :
// skipping more code...
$nestedData[] = "
<select class='form-control changeStatus' name='status'>
<option value=''>--Select--</option>
<option value='1|$client_id' $statusMsg1>Active</option>
<option value='2|$client_id' $statusMsg2>Blocked</option>
</select>";
Now the loaded data is look like this :
Now I want to call the an Ajax request when html selected option value is change. It's calling Ajax request successfully by bellow code.
jQuery code for jQuery Data Table and My Ajax Request :
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"server_processing.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
}
}
} );
$("#employee-grid").on('change', function() {
var status = $('.changeStatus').val();
alert(status);
$.ajax({
url : "<?php echo SITE_URL . 'toplevel/update-data'; ?>",
data : {
'statusChange' : status
},
type : 'POST',
});
});
});
but When I select the option then every time it's passing first option value
For e.g. This selected option tag has these value :
<option value='1|11' $statusMsg1>Active</option>
<option value='2|11' $statusMsg2>Blocked</option>
It's always passing 1|11 value !! It's should be pass my selected option value. I don't understand why it's happening :(
Note : I think using jQuery data table custom jquery code should be use in different way.
Well Guys,
I have solved it. I need to use something like that :
$('#employee-grid').on('change', '.changeStatus', function(){
// testing.....
var status = $('.changeStatus').val();
alert(status);
});
The solution is to use event delegation by providing selector for target element as a second argument in on() call.

Fill jQuery DataTables with drop down and PHP

I'm working with DataTables and this is my scenario:
1)I've got a drop down menu with some user's name and their proper ID;
2)I've got an empty DataTable;
3)I would like to detect user's ID selecting one row from drop drown menu, pass it to server_processing.php(DB query) using data: property of DataTables and display DB query's result back in Data Table.
Code for drop down:
<select id="selezione_user" name="selezione_user" class="select2 form-control">
<option value="">Seleziona</option>
<?php $query=mysql_query("SELECT user_id,nome FROM user ORDER BY nome",$conn);
while($row=mysql_fetch_array($query)){
echo "<option value='$row[user_id]'>$row[nome]</option>";
}?>
</select>
Code for DataTable (HTML):
<table class="table table-striped" id="prova">
<thead>
<tr>
<th>User</th>
<th>Comune</th>
<th>Mail</th>
<th>Stato</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Code for DataTable (JS)
$(document).ready(function() {
var oTable = $('#prova').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/server_processing.php",
"data": {
"user_id": null //set to show empty DataTable
}
},
});
$('#selezione_user').change(function() {
aoData.push({
"user_id": this.value
})
});
});
But the code above doesn't work and this problem is driving me crazy, I hope someone will help me.
Thanks to all.
Giacomo.
EDIT
I solved my problem using removing data: and changing DataTables(JQuery) function in this way:
$('#selezione_centri').change(function() {
var valore = this.value;
var string = ('scripts/server_processing.php?id_professionista='+valore);
table.ajax.url(string).load();
table.reload();
});
I think you should check the row
echo "<option value='$row[user_id]'>$row[nome]</option>";
Try changing it to
echo "<option value='".$row["user_id"]."'>".$row["nome"]."</option>";
This is somewhat explained here: Accessing arrays whitout quoting the key , the php array keys need to be quoted. This is merely a longshot here!
For more precise debugging (if this is not enough), you should provide the php code.

Cannot use fnAddData when table is empty

I'm using a table with the jquery dataTable plugin.
When I use the function fnAddData it works, except when the table is empty. Then, I get this error :
Cannot read property 'className' of undefined
This is how I add my data:
$("#table-1").dataTable().fnAddData([
data[0],
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7],
data[8],
]);
And I have the same problem with fnDeleteRow with this error message:
Cannot read property 'nTr' of undefined
Here's how I use fnDeleteRow, I have no trouble when the table is not empty...
$("#table-1").dataTable().fnDeleteRow(tr)
where tr is a selector.
Am I missing something?
Here's my HTML tab with one last row :
<table id="table-1" class="table table-hover table-nomargin table-colored-header dataTable" aria-describedby="table-1_info">
<thead>
<tr role="row">
<th class="sorting" role="columnheader" tabindex="0" aria-controls="table-1" rowspan="1" colspan="1">Pays</th>
</tr>
</thead>
<tbody role="alert" aria-live="polite" aria-relevant="all">
<tr class="odd">
<td class=" sorting_1">
<div id="address23name">test</div>
</td></tr></tbody></table>
And here's my JS
$("#deleteAddressButton").click(function(){
var id = $("#deleteAddressId").val();
$.post("/Contacts/deleteAddress",
{data: id}, function(data) {
var id = $.parseJSON(data);
var tr = $("tr:has(td:has(div:contains(\"address\" + id + \"Name\")))");
$("#table-1").dataTable().fnDeleteRow(tr)
});
})
jQuery doesn't allow DataTables to access the data in the way that it prefers. In order to give it the node that it wants, you will probably need to apply [0] or .get(0) to the end of your jQuery object. That is actually what jQuery returns -- an object -- and normally exactly what you would be comfortable working with.
DataTables wants a node.
Here are some links that show the developer giving hints about how to access the data in different circumstances -- but with the same error in the 2nd link:
here
and
here
The moral of the story is that if DataTables is expecting a table "node", you need to do some extra footwork to remove the extra jQuery container that it is placed within.
Your code would, therefore, look like this and I believe should handle your error condition. Otherwise, be sure to search for your error and function name on DataTables.net. That forum is very active and helpful.
var tr = $("tr:has(td:has(div:contains(\"address\" + id + \"Name\")))");
$("#table-1").dataTable().fnDeleteRow(tr[0])
or
var tr = $("tr:has(td:has(div:contains(\"address\" + id + \"Name\")))");
$("#table-1").dataTable().fnDeleteRow(tr.get(0))
or of course, add it to the end of your lengthy $("tr:has...) statement.
Option 2:
Just hide the row you want to delete
If these ideas don't help, you may find allan's answers here insightful.
Here's a simple jsfiddle, which allows you to add a row to an empty table:
http://jsfiddle.net/7UZGM/
So what's different about your table? When you say "empty", does it still have a thead/tr/th section and an empty tbody section? These are required for datatables to work properly.
$('#dt').dataTable();
$('#btn').on('click',function() { addData(); });
function addData()
{
$("#dt").dataTable().fnAddData([
"col 1", "col 2", "col 3"]);
}

Categories

Resources