Using datatables to display json file data - json

I tried many solution which are available in stack overflow but any single solution is not useful to me. Here is my code which I am trying still now.
HTML
<table id="example1" class="table table-bordered">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody></tbody>
</table>
Json file data
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
....
}
Datatables code
var table;
$(function () {
table = $('#example1').DataTable({
"processing": true,
"serverSide": true,
"ajax" : {
"url" : "../apps/language/fr/fr.json",
"dataSrc" : function (json) {
console.log(json ? json.length : 'json_data is null or undefined');
$.each(json, function( index, value ) {
//console.log(index + "^_^" + value)
var html = "<tr>";
html += "<td>" + index + "</td>";
html += "<td>" + value + "</td>";
html += "<td><a href='javascript:void(0);' class='btn btn-sm btn-primary waves-effect waves-light edit'>EDIT</a></td>";
html += "</tr>";
var row = $(html);
$("#example1 tbody").append(row);
});
}
}
});
});
Can you please help me where I am wrong? I need data in table format with pagination. Same like datatables. I already load databables library. I am also getting length error in js while I used this code. Uncaught TypeError: Cannot read property 'length' of undefined

Related

JSON array into HTML table

Looking for a solution to achieve an HTML table that takes the "title" from the JSON file and puts it in the first column of a 2 column table and the second column has the "description".
The description has to be tier as bullet points as it is an array within an array in the JSON file. The current way it is working is that it is one big block of data in the second column which looks like a giant sentence. I've tried putting each bullet point into its separate key pair but it is not feasible as it is time-consuming. Is there an option for an if statement that iterates over the array within an array? Open for other script alternatives.
var data = [
{
"title": "title1",
"description":["description1","description2"]
},
{
"title": "title2",
"description":["description3","description4"]
}
]
$(document).ready(function(){
var list = '';
$.each(data, function(key, value){
list += '<tr>';
list += '<td>'+value.title+'</td>';
list += '<td>'+value.description+'</td>'
list += '</tr>';
});
$('#table1').append(list);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="table1">
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</table>
Your current method is fine. You just need to add an $.each inside an $.each:
$(document).ready(function () {
$.getJSON("data.json", function (data) {
var list = '';
$.each(data, function (key, value) {
list += '<tr><td>' +
value.title +
'</td><td><ul>';
$.each(value.description, function (key, value) {
list += "<li>" + value + "</li>";
})
list += '</ul></td></tr>';
});
$('#table1').append(list);
});
});
var data = [{
"title": "title1",
"description": ["description1", "description2"]
},
{
"title": "title2",
"description": ["description3", "description4"]
}
]
$(document).ready(function() {
var list = '';
$.each(data, function(key, value) {
list += '<tr><td>' +
value.title +
'</td><td><ul>';
$.each(value.description, function(key, value) {
list += "<li>" + value + "</li>";
})
list += '</ul></td></tr>';
});
$('#table1').append(list);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="table1">
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</table>
EDIT: Improved Version:
JSFiddle

How to clear previous search result shown by ajax success?

I wanted to clear all the search result shown by ajax search like when the user type for next query it will update it.
$(document).ready(function(){
var text;
$("#button").on('click',function (e) {
e.preventDefault();
var q=$("#q").val();
$.ajax({
url: "/search",
data: {q:q},
type: "GET",
dataType : "json",
success: function(result) {
var event_data = '';
for (var i = 0; i < result.length; i++) {
event_data += '<tr>';
event_data += '<td>' + '<img src=' +result[i]['video']['thumbnail_src']+ '></img>' +'</td>';
event_data += '<td>' +result[i]['video']['title']+'</td>';
event_data += '<td>' +result[i]['video']['duration']+ '</td>';
event_data += '<td>' + '<a href' +result[i]['video']['url']+ '>'+ "Download" +'</a>' +'</td>';
event_data += '</tr>';
} $("#list_table_json").append(event_data);
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
},
always: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
});
This is my html file for table where i was appending result from ajax success, can you guys let me know another technique for this. I wanted to clear previous result and update the new result.
Search
<table class="table table-responsive table-hover table-bordered" id="list_table_json">
<thead>
<tr>
<th>Thumbnail</th>
<th>Title</th>
<th>Duration</th>
<th>Download</th>
</tr>
</thead>
On the start of the success handler, use the below code if you want to keep the first tr (headings) and remove the rest of the data
$("#list_table_json").find("tr:gt(0)").remove();
or use if you want to remove everything
$("#list_table_json").empty();
or another way to remove everything
$("#list_table_json").html('');
How to use?
success: function(result) {
$("#list_table_json").find("tr:gt(0)").remove();
var event_data = '';

Populate HTML table with JSON data

We would be grateful for some guidance, [we are early into coding] and have looked at lots of examples but can cannot get our JSON to import into the table.
At that moment we have the table data in-line however a correctly formatted JSON file is now available and automatically updates and we want to load it into the table on the fly when the page is loaded.
This is an example of what were currently use:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
var data = [
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
];
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
</script>
There are a lot more lines of data, the table has CSS styling and applies the sortTable(n) function to the Headers. It displays perfectly, looks and functions like we want,
We've Googled [lots] and tried various load / populate scripts and attempted to get the example on w3schools working - https://www.w3schools.com/js/js_json_html.asp - alas we're fairly new to this.
Our JSON file /assets/sample.JSON is correctly formatted and meets the requirements.
How do we do a simple import of the JSON to populate the table id="gable"?
Ok, so in this solution I am going to assume that your external json file is called 'example.json'
Your external file should look something like this
example.json:
[
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
]
The html remains the same all the changes have been made in the script tags. I split the functionality into 2 new functions. The first function (get_json_data) gets the json data from the external json file. The second function (append_json) appends the data to the table.
I have put comments throughout the code to explain what everything is doing. if you have any questions or if something is unclear let me know.
here is the code for the html file:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
//first add an event listener for page load
document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load
//this function is in the event listener and will execute on page load
function get_json_data(){
// Relative URL of external json file
var json_url = 'example.json';
//Build the XMLHttpRequest (aka AJAX Request)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {//when a good response is given do this
var data = JSON.parse(this.responseText); // convert the response to a json object
append_json(data);// pass the json object to the append_json function
}
}
//set the request destination and type
xmlhttp.open("POST", json_url, true);
//set required headers for the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// send the request
xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
}
//this function appends the json data to the table 'gable'
function append_json(data){
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
}
</script>
you can have a function to create the table independent from your data fields:
function updateTable(tableId, jsonData){
var tableHTML = "<tr>";
for (var headers in jsonData[0]) {
tableHTML += "<th>" + headers + "</th>";
}
tableHTML += "</tr>";
for (var eachItem in jsonData) {
tableHTML += "<tr>";
var dataObj = jsonData[eachItem];
for (var eachValue in dataObj){
tableHTML += "<td>" + dataObj[eachValue] + "</td>";
}
tableHTML += "</tr>";
}
document.getElementById(tableId).innerHTML = tableHTML;
}

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>

How to show Json data to the dialog box in html

I am a beginner in the ajax, dom, jsonm etc in web application. my project is to use jquery UI to parse json data and show all of data from database and retrive one data by id, it's part of create, retrieve, update, and delete. so retrieving is key function here. I can get all data and populate datatable with all data no problem.
"aoColumns" :[
{"mData" : "image"},
{"mData" : "name"},
{"mData" : "type"},
{"mData" : "description"},
{"mData" : "price"},
{"mData" : "id",
"mRender" : function(data, type,full)
{return '<a href="#" id="'+ full.id +
'" class="id">Details</a>'; }
}
-->to fetch all the data
var findById= function(id) {
console.log('findById: ' + id);
$.ajax({
type:'GET',
url: rootUrl + '/' + id,
dataType: "json",
success: renderList
});
};
var renderList = function(data){
var list = data == null?[] : (data instanceof Array ? data : [ data ]);
///////////////////////////////////
solution1//////////////////////////////////////////////////
$.each(list, function(index, pet){
var row="<tr>" + "<td>" + pet.type + "</td>"
+ "<td>" + pet.price + "</td>"
+ "<td>" + pet.contact_no+ "</td>"
+ "<td> "+ pet.contact + "</td>"
+ "</tr>";
//$(tblRow).appendTo("#entrydata tbody");
$(row).appendTo('dialogTable tbody');
});
to retrieve more details
the result(in xml) show this if I click the "details " link by checking element,
<pet>
<contact>bob.hoskins#lgfriday.com</contact>
<contact_no>5-(254)756-8567</contact_no>
<description>Great companion for up to 75 years</description>
<id>42</id>
<image>bird</image>
<name>Amazon</name>
<price>40</price>
<type>BIRDS</type>
</pet>
(failed)
net::ERR_CONNECTION_REFUSED
the data is coming back in MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML so I can check data type easily but cant make connection to it to show in dialog box
<div id="dialog" title="More Information">
<table id="dialogTable" style="width: 350px;">
<thead>
<tr id="findById">
<th>Type</th>
<th>Price</th>
<th>Contact</th>
<th>Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I resolved the problem. I had set var rooturl = http://localhost/xxx/rest/xxx"; instead of rooturl = "http://localhost:8080/xxx/rest/xxx" . It solved the cross origin connection and connection failure problem and now it renders.