using a json file to create a table in html - javascript

I realise that this question has been asked a lot. Unfortunately, I haven't been able to work out how to properly implement any of the solutions.
So I have 3 files all in the same folder. 1 python script that creates the json file based on data scraped online.
Python script:
jsonFile = {"title": bookTitle, "author": author}
jsonArray.append(jsonFile)
with open(data.json, 'w) as file:
json.dump(jsonArray, file)
The JSON file ends up looking like this:
[{"name": "Foo", "author": "bar"},
{"name": "Bart", "author": "Simpson"},
{"name": "Homer", "author": "Simpson"}]
Now I'm trying to get that data into my index.html and to display it in various ways such as a table.
Index.html:
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="table-container">
<table id="table">
<tr>
<th>Name</th>
<th>Author</th>
</tr>
</table>
</div></div>
<script>
var data = $.getJSON(data.json);
var table = document.getElementById("table");
data.forEach(function(object) {
var tr = document.createElement("tr");
tr.innerHTML = "<td>" + object.title + "</td>" + "<td>" + object.author + "</td>"
table.appendChild(tr);
});
</script></body>
I appreciate any pointers someone might be able to give. Side question: do I need to use JQuery? Is there a better way?

Checking if you need jQuery is easy via http://youmightnotneedjquery.com/
Based on their recommendation your JS-code would look like this:
var request = new XMLHttpRequest();
request.open('GET', 'data.json', true);
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response); //this is your JSON that is returned from your API (python)
var table = document.querySelector('#table');
for (var i = 0; i < data.length; i++) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.title + '</td>' + '<td>' + object.author + '</td>'
table.appendChild(tr);
}
} else {
// ERROR!!
}
};
request.onerror = function () {
// There was a connection error of some sort
};
request.send();

Related

Populating an HTML table from an external XML

I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn't solve. I have a XML that looks like this:
<root>
<document-id>
<author>Tom Riddle</autor>
<title>abzy</title>
<year>1995</year>
</document-id>
<document-id>
<author>Tom Riddle</autor>
<title>abzy</title>
</document-id>
<document-id>
<author>Tom Riddle</autor>
<year>1995</year>
</document-id>
</root>
I want to dynamically access the data inside the XML and create a table while doing so. It works fine for the one DOM Element all documents share, but it gives me an error as soon as I include year or title. I guess it's because the tags are empty in some parts of the tree. Is there a way to ignore empty tags and only write something in the column if there is a value inside? Thank you for your time and knowledge.
THIS IS THE ASSOCIATED HTML
<body>
<header>
<h1>Reading Data from XML Files</h1>
</header>
<main>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<table id="demo">
</table>
</main>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
myFunction(this);
}
xhttp.open("GET", "books.xml");
xhttp.send();
}
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("document-id");
console.log(x)
let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
for (let i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
"</tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
Check for existence before you try to access the children.
function getText(node, tag) {
var elem = node.getElementsByTagName(tag);
return elem ? elem.[0].childNodes[0].nodeValue : '';
}
for (let i = 0; i <x.length; i++) {
var cells = ['author', 'title', 'year'].map(function (tag) {
return "<td>" + getText(x[i], tag) + "</td>";
}).join("");
table += "<tr>" + cells + "</tr>");
}
try this with in line solution to check if tag exist in xml
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("document-id");
console.log(x)
let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
for (let i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"</td><td>" + ((x[i].getElementsByTagName("title")[0] == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue ) +
"</td><td>" +
((x[i].getElementsByTagName("year")[0] == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue ) +
"</tr>";
}
document.getElementById("demo").innerHTML = table;
}

Fetch data from public API using dynamic url

I want to fetch data from this public API which takes a parameter. I would like to then display this fetched data in a table.
I also have two buttons backwards and forward which change the parameter for the URL and therefore display a new set of data in the table.
The forward button adds 1 to the parameter and the backwards button substracts 1 from the parameter of the API url.
This is my current code:
HTML code:
<div align="center">
<button style="display:inline" onclick="backFunc();">Back</button>
<p id="gameweek" style="display:inline;"></p>
<button style="display:inline" onclick="forwardFunc();">Forward</button>
<br>
<br>
<table id = "fixtures_table">
<tbody id ="tbody"></tbody>
</table>
</div>
This is my javascript code:
var request = new XMLHttpRequest();
request.withCredentials = true;
var urlparam = "1";
roundnum = 0;
var gameweek;
request.open("GET", "https://api-football-
v1.p.rapidapi.com/v2/fixtures/league/524/Regular_Season_-_" + urlparam);
request.setRequestHeader("x-rapidapi-host", "api-football-v1.p.rapidapi.com");
request.setRequestHeader("x-rapidapi-key",
"733394c196mshc5cdb3fe20f1ec5p162525jsnc81f4950b7d6");
var data
request.onload = function () {
data = JSON.parse(this.response);
gameweek = document.getElementById('gameweek');
gameweek.innerHTML = data.api.fixtures[roundnum].round;
if (request.status >= 200 && request.status < 400) {
var tbody = document.getElementById('tbody');
var table = document.getElementById('fixtures_table');
data.api.fixtures.forEach(fixtures => {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + fixtures.homeTeam.team_name + '</td>' +
'<td>' + fixtures.goalsHomeTeam + '</td>' +
'<td>' + "VS" + '</td>' +
'<td>' + fixtures.awayTeam.team_name + '</td>' +
'<td>' + fixtures.goalsAwayTeam + '</td>' +
'<td>' + fixtures.status;
tbody.appendChild(tr);
table.appendChild(tbody);
});
}
console.log(data);
}
function forwardFunc(){
}
function backFunc(){
}
However I am not sure how to make the forward and backwards function fetch the new set of data using the updated parameter and display those results in the table instead of the old ones.

Refer specific row on click of button in table data fetched from JSON using only JavaScript

I am learning AJAX and not able to find how to refer a particular row in a table which is fetched from a .json file. Actually I want the respective data on click of the respective edit button in the row. It should be displayed in the <p> tag just below the table.
Heres my script
<script>
function myFunction() //on click function to fetch data from json
{
var counter;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(xhttp.readyState == 4 && xhttp.status == 200)
{
var data = JSON.parse(xhttp.responseText);
mydata(data);
}
};
xhttp.open("GET", "employee.json");
xhttp.send();
counter ++ ;
}
function mydata(data){ //data to be shown and fetch
var output = "<table>";
var output = "<th>Employee Code</th>" +
"<th>Name</th>" +
"<th>Joining Date</th>" +
"<th>Salary</th>"+
"<th>Edit</th>";
//var i in each items[i]
for(var i in data)
{
output += '<tr>' +
'<td>' + data[i].empcode + '</td>' +
'<td>' + data[i].name + '</td>' +
'<td>' + data[i].joining + '</td>'+
'<td>' + data[i].salary + '</td>' +
'<td>' + '<button onclick="edit()">Edit</button>' +
'</tr>';
}
output +="</th>" + "</th>" + "</th>" + "</th>" + "</th>";
output += "</table>";
document.getElementById('demo').innerHTML = output;
function edit(){
document.getElementById("para").innerHTML = data[1].empcode;
}
}
function edit(){ //edit function to display related data from json file. Right now i can only display data which i mentioned in editTextData().
var edit = new XMLHttpRequest();
edit.onreadystatechange = function(){
if(edit.readyState == 4 && edit.status == 200){
var editData = JSON.parse(edit.responseText);
editTextData(editData);
}
};
edit.open("GET", "employee.json", true);
edit.send();
}
function editTextData(textData){
document.getElementById("para").innerHTML = textData[2].empcode;
}
</script>
This is the JSON data :
[{
"empcode" : 1,
"name": "sid",
"joining" : "13 march",
"salary" : 60000
},
{
"empcode" : 2,
"name": "andrew",
"joining" : "15 march",
"salary" : 65000
},
{
"empcode" : 3,
"name": "blake",
"joining" : "18 march",
"salary" : 70000
}
]
This is the html code :
<h1>AJAX Employee</h1>
<div>
<table id="demo"> </table>
</div>
<button onclick="myFunction()" ">Fetch Info</button>
<p id="para"> </p>
This is the result i am getting
Result table after clicking fetch button. When i click any edit button it shows the 3rd employee number
Your edit handler can figure out which button was clicked, which row it belongs to, and which empcode that was. The key is the this value that gets passed into the edit handler.
You're assigning the handler inline, which isn't ideal, so you will need to make a change to that part:
'<td>' + '<button onclick="edit(this)">Edit</button>'
Now the button is being passed into edit as the first parameter, so:
function edit(btn) { //edit function to display related data from json file.
// get the TR that this button is in
var tr = btn.parentNode.parentNode;
// get the collection of tds
var tds = tr.querySelectorAll("td");
// get the contents of the first TD, that should be the empcode
var empcode = tds[0].innerText;
// do whatever you need to with empcode, or the other values in this record
console.log("empcode = " + empcode + ", name = " + tds[1].innerText);
}

How do I include a header in a generated table of my javascript?

I receive in my javascript a json data that it is converted to a html table.
The script is working.. but how do I include a header in my table?
Here is the code:
<script>
$(document).ready(function(){
$('#id_adv').DataTable();
$('#id_adv').on('click','.btn',function(){
var currow = $(this).closest('tr');
var result = currow.find('td:eq(1)').text();
$.get('{% url "prop_table" %}', {var1:result}, function (data_prop) {
var data = data_prop['data_prop']
var data_json = JSON.parse(data);
var html = "";
for (var i = 0; i < data_json.length; i++) {
html += "<tr><td>" + data_json[i].fields.var1 + "</td><td>" + data_json[i].fields.var2 + "</td><tr>";
}
$('#id_prop').html(html);
})
document.getElementById('total').innerHTML = result;
});
});
</script>
Slight modification to your existing code to add a header. (I've cut out your usage of eval and just kept in the relevant part to create the HTML table header)
<script>
....
var html = "";
html += "<tr><th>Header 1</th><th>Header 2</th><tr>";
for (var i = 0; i < data_json.length; i++) {
html += "<tr><td>" + data_json[i].fields.var1 + "</td><td>" + data_json[i].fields.var2 + "</td><tr>";
}
$('#id_prop').html(html);
....
</script>
This should add a header to your table.
And I agree with the comment in your question, use the built in JSON parsing. eval is just asking to be exploited.
I think that you can add the header after create the table. The createTHead() method creates an empty element and adds it to the table. I.e.:
<script>
function createHeader() {
var table = document.getElementById("myTable");
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "<b>This is a table header</b>";
}
</script>

Unable to convert JSON response into HTML table using javascript

I am getting the below json response from the servelet for the ajax request but unable to convert the data into table and display it in jsp.
[{
"ordernumber": 123456,
"slotservice": "Collection ",
"deliverydate": "Jul 1, 2017"
}]
Below is my javascript which does the ajax request,
function addData(){
if(window.XMLHttpRequest) { //Assuming you're not on one of the old IEs.
var xhttp = new XMLHttpRequest();
xhttp.open("POST","Order",true);
var formData = new FormData(document.getElementById('orderform'));
xhttp.send(formData);
console.log('This is Ajax request to the order controller');
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && (xhttp.status == 200)) {
var myArr = JSON.parse(xhttp.responseText);
console.log(JSON.stringify(myArr));
var tr;
for (var i=0;i<myArr.length;i++){
tr = $('<tr/>');
tr.append("<td>"+myArr[i].ordernumber+ "</td>");
tr.append("<td>"+myArr[i].slotservice+ "</td>");
tr.append("<td>"+myArr[i].deliverydate+ "</td>");
$('ViewOrderResultContainer').append(tr);
console.log
}
}
}
}
else console.log('not working');
}
Below is the table defined in my index.jsp
<div id="divOrderResultContainer">
<table id="ViewOrderResultContainer" border=1>
<thead>
<tr>
<th>OrderNumber</th>
<th>ServiceType</th>
<th>DeliveryDate</th>
</tr>
</thead>
</table>
</div>
Can anyone explain me what i am doing wrong here and how can i get the expected results.
Edit 1: I have now updated my servlet like below but its still not printing the HTML table response in my jsp
function addData(){
if(window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && (xhttp.status == 200)) {
var jsonorderdata = JSON.parse(xhttp.responseText);
for (x in jsonorderdata)
txt += "<tr><td>" + myObj[x].ordernumber+ "</td><td>" +
myObj[x].slotservice+ "</td><td>" + myObj[x].deliverydate+ "</td>"
"</tr>";
}
document.getElementById("ViewOrderResultContainer").innerHTML =
txt;
}
}
xhttp.open("POST","Order",true);
var formData = new FormData(document.getElementById('orderform'));
xhttp.send(formData);
}
else console.log('not working');
}
Additionally my javascript gives 304:not modified response in chrome , can anyone please help me on how to get the table in jsp.
You are missing selector in $('ViewOrderResultContainer').append(tr);. Add # to select an element by id
$('#ViewOrderResultContainer').append(tr);

Categories