import Json to html (table) - javascript

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>

Related

How to put ajax result to html table?

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
//...
})
})

How to create AJAX POST button for multiple data in table?

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");
}
});
});

DataTables does not display data

I'm trying the jQuery DataTables control. The problem is that I cannot display data.
HTML is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTest.aspx.cs" Inherits="JsonTest.DataTablesTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
</head>
<script>
var d = [
{ "Id": 3, "ActivityID": 91, "OperationType": 0, "UserID": 4183, "Comments": "", "ActionDate": "2006-03-19T12:26:01.673" },
{ "Id": 4, "ActivityID": 91, "OperationType": 4, "UserID": 4183, "Comments": "", "ActionDate": "2006-03-19T12:26:01.673" },
{ "Id": 5, "ActivityID": 92, "OperationType": 0, "UserID": 5688, "Comments": "", "ActionDate": "2006-03-20T12:05:40.563" }
];
$(document).ready(function () {
$('#example').dataTable({
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"dataSrc": "",
"contentType": "application/json; charset=utf-8"
},
//"data": d,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
var table = $('#example').DataTable();
alert('There are' + table.data().length + ' row(s) of data in this table');
});
</script>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
If I comment out the Ajax code and uncomment the
//"data": d,
It works fine. The d variable is the JSON data that I get from the service using firefox->developer->network->xhr->response dialog.
I read many posts and I tried many things but I can't make it work.
Any help?
Thanks.
EDIT:
Service Code:
namespace JsonTest
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetData()
{
var list = ActivityHistory.GetAll(); // List<ActivityHistory>
var s = Newtonsoft.Json.JsonConvert.SerializeObject(list);
return s;
//return "{\"aaData\":" + s + "}";
}
}
}
EDIT 21/07/2015:
I've done some changes in HTML code and it's working with a little bug. While loading I see for a moment at the top of the page the headers of the table element (ActivityHistoryID, AH_ActivityID, AH_OperationType, AH_UserID, AH_Comments, AH_TimeStamp). After that it's working fine (for 60.000 rows!!!).
The new-changed code is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTest.aspx.cs" Inherits="JsonTest.DataTablesTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
<script>
$(document).ready(function () {
$.ajax({
type: "post",
url: "WebService1.asmx/getdata",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = $.parseJSON(data.d);
$('#example').DataTable({
"data": myData,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
My last hope is that I 'm using JQuery 1.10.2 instead of 1.11.1 which is in the examples of datatables site.
It 's the third day of trying and still I cannot figure it out.
EDIT 22/7/2015
That is the code that works. Far from examples.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTestWorking.aspx.cs" Inherits="JsonTest.DataTablesTestWorking" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.11.3.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
<script>
$(document).ready(function () {
$('#example').hide();
$.ajax({
type: "POST",
url: "WebService1.asmx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#example').show();
var myData = $.parseJSON(data.d);
$('#example').DataTable({
"data": myData,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
Modify your ajax call - make it asynchronous
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"async" : false,
"contentType": "application/json; charset=utf-8"
}
Now your data will be binded only after the ajax request is completed from your service.
It worked for me.
In your server-side code , use printwriter to send the json data as a string.
PrintWriter out = resp.getWriter();
result.put("iTotalRecords", total);
result.put("iTotalDisplayRecords", totalRecordCount);
result.put("aaData", array);
resp.setContentType("text/jsonp");
out.print(result);
Or else use gson to conver your list of objects to json array
e.g.,
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(dataTableObject);
out.print(json);
NOTE : aaData needs to be set else your data will not be binded.
According to this post option contentType: 'application/json; charset=UTF-8' and type: 'POST' is indeed required to invoke an ASP.NET AJAX web method.
However, in order to send JSON-encoded parameters rather than URL-encoded parameters, you need to use ajax.data option to encode parameters into string in JSON format.
$('#example').dataTable({
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"contentType": "application/json; charset=utf-8",
"dataType": "json",
"data": function ( d ) {
return JSON.stringify( d );
},
"dataSrc": "d",
},
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});

Create table if data from ajax not empty

First I have HTML:
<div class="showTable" style="display: none;">
<table id="example" class="table table-responsitive" cellspacing="0" width="100%" style="margin-top:30px;">
<thead>
<tr>
<th>ID</th>
<th>Broj računa</th>
<th>Kupac</th>
<th>Datum izdavanja</th>
<th>Rok za plaćanje</th>
<th>Status</th>
<th></th>
</tr>
</thead>
</table>
</div>
<div class="showInfo" style="display: none">
</div>
After that I write JS:
$(document).ready(function() {
drawVisualization();
});
function drawVisualization() {
console.log('proba');
$.ajax({
url: "getracuni.php",
type: "POST",
async: true,
dataType: "html",
success: function(json) {
console.log(json);
if (!json.data){
json.data = [];
$('.showInfo').show();
} else {
var podaci = json.data;
$('.showTable').show();
showTable(podaci);
}
},
error: function(data) {
console.log(data);
}
});
};
so here I try to make this:
1. IF data from ajax is not empty then to create datatable with function showTable(podaci);
2. IF data from ajax is empty then just want to show div class 'showInfo'.
My showTable(podaci) function is:
function showTable(podaci) {
$('#example').dataTable({
data: podaci.data,
paging: false,
"dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">',
bfilter: false,
"oLanguage": {
"sInfo": 'Ukupno _END_ računa.',
"sInfoEmpty": 'Nema podataka o računima',
"sEmptyTable": "Nemate račune, dodajte klikom na dugme ispod.",
},
// end ,
"columns": [{
"data": "ID"
}, {
"data": "br"
},
{
"data": "kupac"
},
{
"data": "datum"
},
{
"data": "rok"
},
{
"data": "status"
},
{
"data": "akcija"
}
],
"columnDefs": [
{
"targets": 6,
"data": "akcija",
"render": function(data, type, full, meta) {
// return data;
return '<div style="float:right;"><div class="btn-group">Izmeni <span class="caret"></span><ul class="dropdown-menu"><li>Izmeni</li><li>Pošalji</li><li>Opomeni</li><li>Plaćeno</li><li>Stoniraj</li><li>Kopiraj</li><li>Obriši</li></ul></div> <i data-toggle="modal" data-target="#delete" class="fa fa-times"></i></div>';
}
},
{
"targets": 0,
"visible":false
}
]
});
}
Also I get data from ajax in this JSON format:
{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}
I think that I write everything fine but when I try to run this code I just get blank screen. SO anything wont to show there...
Change your condition
if (!json.data) to if (json.data!=null)

Return DataTable row values onClick

I have been studying and working endlessly with DataTables the past 2 weeks and gotten to a brick wall now. The issue I am trying to sort out is how I can pass values in a particular row when the button for that row is clicked on. As at now with my limited knowledge on DataTables and JQuery, when I have like 2 to 3 buttons in different rows and I click on each one, the value they all return back is the values in the first row only. Not sure how best I can solve this or where my error might lie. Any guide or help would be much appreciated. Thanks
<script type="text/javascript" charset="utf-8">
<!-- ------------------- Extract all Alerts ---------------------- -->
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "description" },
{ "data": "priority" },
{ "data": "acknowledged", render: function( data, type, row ) {
if (data == "0" && row.priority > "2") {return '<div><form method="post" id="'+row.source + row.eventid+'" action="include/db_conn.php"> <input type="hidden" id="evtid" value ="'+row.eventid+'"> <input type="hidden" name="source" value ="'+row.source+'"> <INPUT TYPE="text" name="username" size="3" maxlength="3"> <input type="submit" name="'+row.source + row.eventid+'" onClick="ackbutton(this)" value="Ack Alert"></form></div>';
} return data;
}
}
],
});
setInterval (function(){
$.getJSON("data/json_data.txt", function (pcheckdata){
alertTable.clear().draw();
alertTable.rows.add(pcheckdata.alert).draw();
alertTable.columns.adjust().draw();
});
}, 10000);
});
function ackbutton() {
//e.preventDefault();
var $this = $(this);
var getvalues = $('#evtid').val();
alert(getvalues);
}
</script>
HTML:
<body>
<div class="all_tables">
<table id="alert-table" class="display" cellspacing="0">
<thead class="t-headers">
<tr>
<th>Server</th>
<th>Host</th>
<th>Description</th>
<th>Priority</th>
<th>Acknowledged</th>
<th>Eventid</th>
</tr>
</thead>
</table>
</div>
</body>
JSON
{
"alert": [
{
"source": "Server1",
"host": "host1",
"description": "Engine Alive",
"priority": "4",
"triggerid": "14531",
"acknowledged": "0",
"eventid": "3419709",
"value": "1"
},
{
"source": "Server2",
"host": "host2",
"description": "webapp down",
"priority": "2",
"triggerid": "18027",
"acknowledged": "1",
"eventid": "4012210",
"value": "1"
}
],
"error": []
}
You need to find the input with id 'evtid' in closest div of currently clicked ack button.
Example:
$(document).on('click','.submitButton',function(e){
e.preventDefault();
debugger
var $this = $(this);
var curEventId = $this.closest('div').find('#evtid');
var getvalues = curEventId.val();
alert(getvalues);
return false;
});
You can also use closest form instead of div.
var curEventId = $this.closest('form').find('#evtid');

Categories