I was able to get result from MVC controller using ajax, it returns me json data. Now i need to put it to html table in view, how can i do it?
function getClassificators(){
$.ajax({
url:"/Employee/GetClassificationLevels",
type:"GET",
success: function(result){
if(Array.isArray(result) && result.length > 0){
var eachRes = result.map(function(classificator, i){
return {
levels: classificator.Level,
name: classificator.Name,
score: classificator.Score,
sublevel_info : classificator.EmpEvaluation_SubLevelView.map(function(sublevelinfo, i){
return {sublevel_name: sublevelinfo.Name};
})
};
});
}
},
error: function(err){
console.log(err);
}
});
}
console shows:
[{
{levels:0, name: "level4", score:3, sublevel_info:{sublevel_name:"sublevel4"}}
}]
Expected output is html table.
Take a look at DataTables.js.
It has ajax support out of the box, and it's raelly easy to use.
Here an example
var dtTickets = $("#dtTickets");
datatable = $(dtTickets).DataTable(
{
"order": [[0, "desc"]],
"createdRow": function (row, data, index) {
$(row).data("userId", #id);
$(row).data("ticketId", data.id);
$(row).addClass("selectable");
},
"ajax": {
"url": "#Url.Action("TicketsAjax", "User")",
"type": "POST",
"data": function (d) {
// Set here variables for you AJAX POST message.
d.id = #id;
d.companyId = #summary.CompanyId;
d.filtersJson = searchParms.filtersToJson();
console.log(d);
},
"dataSrc": function (response) {
// You can process the response here if needed.
return response;
}
},
"columns": [
{
"className": "text-right"
"data": "id"
},
{ "data": "createDate" },
{ "data": "createUserName" },
{ "data": "title" },
{ "data": "status" },
{ "data": "actionDate" },
],
}
);
Make sure that your table is structured like this
<table>
<thead>
<tr>
<th>test</th>
<th>somecolumn</th>
</tr>
</thead>
-> I have a answer but in pure JS, not in jQuery – Mister Jojo
-> can u share it please? – Valery
it looks like that
suposed HTML:
<table id="my-table">
<thead>
<td>Level</td><td>Name</td><td>Score</td>
</thead>
<tbody></tbody>
</table>
JS:
const Url = '/Employee/GetClassificationLevels'
, myTableBody = document.querySelector('#my-table tbody')
fetch(Url)
.then(resp=> resp.json())
.then(data=>{
// ...
data.forEach(classificator=>{
let eRow = myTableBody.insertRow(-1)
, nCol = 0
eRow.insertCell(nCol++).textContent = classificator.Level
eRow.insertCell(nCol++).textContent = classificator.Name
eRow.insertCell(nCol++).textContent = classificator.Score
//...
})
})
Related
I need to add id property to TR of table data dynamically added with jquery ajax server-side and write data there. how can I do that. I add the Json data coming with the code below to the lines.
"ajax": {
"url": '/Siparis/SiparisleriDoldur/',
"type": 'POST',
"dataType": 'json',
"data": { liste }
},
"columns":
[
{ "data": "MusteriAdi", "name": "Müşteri Adı" },
{ "data": "MalzemeAdi", "name": " Ürün Adı" },
{ "data": "SiparisAdet", "name": "Sipariş Adedi" },
],
i want to do;
<tr id='IdNumber' data-id='IdNumber'>
<td>bla</td>
<td>bla</td>
<td>bla</td>
</tr>
Note: IdNumber is in data(json list)
Given your use of the Datatable library you can use the createdRow property of the settings to amend each row as required. Try this:
$('#yourDatatable').dataTable({
"createdRow": function(row, data, dataIndex) {
let id = data[0]; // amend 'data[0]' here to be the correct column for your dataset
$(row).prop('id', id).data('id', id);
},
"ajax": {
// ...
},
// other settings as normal...
});
I fixed my problem with;
"createdRow": function (row, data) {
var id = data.Id;
$(row).prop('id', id).data('id', id);
$(row).attr('data-id', id).data('data-id', id);
},
im trying to import a json url to html in a table. The problem is when i get the data i get 25 rows i get this on the web console: Object { data: Array[25], paging: Object } I also have the following code which is designed for only one row i guess .And i understand i have Loop over each object, appending a table row with the relevant data of each iteration. The problem is i don´t how to do it, i´m not an expert . Thank you for your help!
This is the data i get on the json url :
{
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
And this my code
<body>
<input type="text" class="txtPagina">
<button class="btnBuscar">Buscar</button>
<table class="tabla" border='1'>
<tr>
<td>created time</td>
<td>permalink url</td>
<td>id</td>
<td>Shares Count</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.btnBuscar').on('click', function (){
var pagina = $('.txtPagina').val();
//Ajax
$.ajax({
type: "GET",
dataType: "json",
url: "https://graph.facebook.com/"+pagina+"/feed?fields=created_time,permalink_url,id,shares& access_token=mytoken",
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
error: function (){
console.log("Error");
}
});
});
});
</script>
</body>
</html>
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
should be
success: function(data){
$.each(data.data, function(i, d){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td><td>'+d.id+'</td>'+s+'</tr>');
});
},
function create(t,attr,parent_node,innerdata){
var dom = document.createElement(t)
for(key in attr){
dom.setAttribute(key,attr[key])
}
dom.innerHTML = innerdata;
parent_node.appendChild(dom)
return dom;
}
window.onload = function () {
var d = {
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
]
}
var tb= document.getElementById('inputTable')
f = {"created_time":1,"permalink_url":1,"id":1,"shares":1}
d['data'].forEach(function(val){
tr_dom = create('tr',{},tb,'')
Object.keys(f).forEach(function(tr){
if(tr in val){
if('shares' == tr)
td_dom = create('td',{},tr_dom,val[tr]['count'])
else
td_dom = create('td',{},tr_dom,val[tr])
}else
td_dom = create('td',{},tr_dom,'')
})
})
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table border='1'>
<thead>
<th>Create Time</th>
<th>permalink_url</th>
<th>id</th>
<th>Share</th>
</thead>
<tbody id="inputTable">
</tbody>
</table>
</body>
</html>
Sorry for the bad title. I am new to Rails and Javascript. I setup a DataTable using child rows following the DataTables documentation using a single ajax call to a JSON file.
I got that all working I now want to use my Rails controller to get the JSON from a Mongo DB. I also have that part working. What I am confused about is probably very simple and I am used to building a Rails table with active record BUT here I had a separate javascript called tests.js with my DataTable definition and the ajax call to a file. Can I now just pass in the JSON from the View somehow? I am not sure how to switch from the ajax call to using the JSON I now have from my controller
$(document).ready(function() {
var table = $('#queryone_table').DataTable( {
"ajax": "/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "transactionType" },
{ "data": "collationId" },
{ "data": "licensePlate" },
{ "data": "description" },
{ "data": "startDate" },
{ "data": "FeedComplete" },
{ "data": "RepoComplete" },
{ "data": "feedProcessingDuration" },
{ "data": "completeDuration" }
],
"order": [[1, 'asc']]
} );
Objects.txt I would now like to be a var from my View? With active record and MySQL I would build the table in the view looping over a dataset from controller but with the child row code already done in javascript I would like to leave that.
full javascript code
$(document).ready(function() {
var table = $('#queryone_table').DataTable( {
"ajax": "/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "transactionType" },
{ "data": "collationId" },
{ "data": "licensePlate" },
{ "data": "description" },
{ "data": "startDate" },
{ "data": "FeedComplete" },
{ "data": "RepoComplete" },
{ "data": "feedProcessingDuration" },
{ "data": "completeDuration" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#queryone_table tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
function format ( d ) {
var foo = '<table id="queryinner_table" cellpadding="5" cellspacing="2" border="1" style="padding-left:50px;" class="table table-striped table-bordered table-hover table-condensed dataTable no-footer sub-table">';
// loop over table rows
var trow = "";
for (var i=0; i< d.nextrow.length; i++) {
var foo2 = '<tr>'+
'<td>Transaction Step:</td>'+
'<td>'+d.nextrow[i].transactionStep+'</td>'+
'<td>'+d.nextrow[i].elapsedSeconds+'</td>'+
'</tr>'
trow = trow + foo2
} //for loop
var foo2 = '</table>';
var res = foo.concat(trow);
res = res.concat(foo2);
return res;
}
This was poorly worded I have started a new project and will ask a few questions based on that code rather than rewrite this one.
I have table like this
<table>
<tr>
<th>User</th>
<th>IP</th>
<th>Action</th>
</tr>
<tr>
<td>Jack</td>
<td>192.168.0.1</td>
<td><button id="check" name="192.168.0.1">Check</button></td>
</tr>
<tr>
<td>Eve</td>
<td>192.168.0.2</td>
<td><button id="check" name="192.168.0.2">Check</button></td>
</tr>
<tr>
<td>Smith</td>
<td>192.168.0.3</td>
<td><button id="check" name="192.168.0.3">Check</button></td>
</tr>
</table>
How to implementation to send POST data IP with AJAX?
I have tried with this code but does not work..
<script>
$('#check').click(function() {
var getIP = $('#check').name();
var dataIP = 'sendIP=' + getIP;
$.ajax({
url: 'url.php',
type: 'POST',
data: dataIP;
success: function () {
alert("Success");
}
});
});
</script>
[UPDATE]
This is Full code for my project.
<script>
$(document).ready(function() {
$('#reportrange span').on('DOMSubtreeModified', function () {
var dariRange = $(this).html();
var SplitRange = dariRange.split("~");
$('#datatable-keytable').DataTable( {
"destroy": true,
"processing": true,
"keys": true,
"order": [[ 6, "desc" ]],
"ajax": {
url: "view.php",
type : 'GET',
data : {
datedari : SplitRange[0].trim(),
datesampai : SplitRange[1].trim()
}
},
"columnDefs": [
{ "width": "5%", "targets": 0 },
],
"columns": [
{ "data": "click_username" },
{ "data": "click_cid" },
{ "data": "click_offer" },
{ "data": "click_ip" },
{ "data": "click_isp" },
{ "data": "click_posttime" },
{ "data": "click_ip",
"render": function (click_ip,data,row) {
var clickid = data.click_cid;
return ('<center><button class="check" id="'+click_ip+'" name="'+clickid+'">Check</button></center>'); //This for Button check
}
},
],
} );
} );
} );
</script>
<script type="text/javascript">
$(document).on('click', '.check',function() {
var dataID = 'sendCID=' + this.name;
var dataIP = this.id;
$.ajax({
url: 'send_data.php',
type: 'POST',
data: dataID;
success: function () {
window.open('http://whatismyipaddress.com/ip/'+dataIP);
}
});
});
</script>
I want to POST var dataID to send_data.php and then if success open new tab to http://whatismyipaddress.com/ip/'+dataIP but does not work with this code,
I hope someone help me to resolve this, thank you
You can't repeat ID's in a page , they are unique by definition, so will need to change to a class
Within an event handler this is the element the event occurred on so in your case this.name would be value needed
// use class selector
$('.check').click(function() {
var dataIP = 'sendIP=' + this.name;
$.ajax({
url: 'url.php',
type: 'POST',
data: dataIP;
success: function () {
alert("Success");
}
});
});
I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)