How To Load JSON file to a HTML Table? Using JavaScript - javascript

My json file, named as "subject.json" contains:
[
{ "subject":"ProgApps", "codeNo":"9594", "courseNo":"IT 312L", "instructor":"Maria Clemente Concepcion" },
{ "subject":"ITCR", "codeNo":"9615", "courseNo":"IT 014", "instructor":"Jonathan Ramirez" },
{ "subject":"ITP2", "codeNo":"9602", "courseNo":"IT 421", "instructor":"Jonathan Ramirez" }
]
This is my function to get data from my json file. But I don't know how load it into my table. I just want to make it more simple because I already search some answers here but they're too complicated for me as a beginner.
function ajaxGetJson() {
var hr = new XMLHttpRequest();
hr.open("GET", "scripts/subject.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
}
}
hr.send(null);
}
I tried several times and all failed. I only know how to use JavaScript but I also tried using jQuery because of their example (answers). But I can't learn jQuery yet because I'm trying to solve this JavaScript so my knowledge about jQuery is very limited.
Sorry RIP English.
This is my html file. It only includes table tag since many people create table just using JavaScript. I attempt to add the headers inside the table so that only data will be loaded. Is that valid?
<body>
<div class="main-div">
<h1>Schedule</h1>
<div id="schedule-container">
<table id="sched-table"></table>
</div>
</div>
</body>

You have your data object loaded. Cool.
Now just do a for loop to print out some gubbins. This is not a full snippet but you should get enough from it.
function ajaxGetJson() {
var hr = new XMLHttpRequest();
hr.open("GET", "scripts/subject.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
formatToTable(data);
}
}
hr.send(null);
}
function formatToTable(var data){
var thisElement = document.getElementById('mytablecontainer');
thisElement.innerHTML = "<table>";
for (var x =0; x <len(data); x++){
thisElement.innerHTML = thisElement.innerHTML + "<tr><td>" + data[x].subject +"</td> <td>" + data[x].codeNo +"</td></tr>";
};
thisElement.innerHTML = thisElement.innerHTML + "</table>";
}
Something along those lines should do. Json.parse creates an object with attributes such as documented in w3 schools

You can try this:
var data = [
{ "subject":"ProgApps", "codeNo":"9594", "courseNo":"IT 312L", "instructor":"Maria Clemente Concepcion" },
{ "subject":"ITCR", "codeNo":"9615", "courseNo":"IT 014", "instructor":"Jonathan Ramirez" },
{ "subject":"ITP2", "codeNo":"9602", "courseNo":"IT 421", "instructor":"Jonathan Ramirez" }
];
var table = document.getElementById('table');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.subject + '</td>' +
'<td>' + object.codeNo + '</td>' +
'<td>' + object.courseNo + '</td>' +
'<td>' + object.instructor + '</td>';
table.appendChild(tr);
});
<table id="table">
<tr>
<th>Subject</th>
<th>CodeNo</th>
<th>courseNo</th>
<th>instructor</th>
</tr>
</table>

Related

Loading data from a json file when an element is selected from a drop down list

Create an application to load districts from a JSON file hosted at the server and list the districts according to a selected province given in a dropdown box.
First, create a form with the followings.
Suitable title
A dropdown list containing all the provinces in Sri Lanka. (Use an
array to store the provinces, the first element is "Please select"
and the rest are provinces)
A div to load districts
Initially, the dropdown list is selected as "Please select".
When you select a province from the dropdown list all the districts relevant to that province will be loaded and displayed in the div with bullets (Hint: <ul><li></li></ul>)
The list of districts should be in a JSON file with the relevant province name.
HTML CODE
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<table>
<tr>
<td>Select a province</td>
<td>
<select id="myselect" onchange="change_myselect(this.value)">
<option value="1">Select province</option>
<option value="2">Western</option>
</select>
</td>
</tr>
</table>
</form>
<p id="demo"></p>
<script>
function change_myselect(sel) {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: sel, limit: 20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "districts.json", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
</script>
</body>
</html>
JSON FILE
{
"province":"Western",
"name":"Colombo",
"name":"Gampaha",
"name":"Kalutara"
}
I have tried creating a simple json file with the data that should be displayed when 'western' is selected from my drop down list. I am not getting any data when I run the code :(
I am getting this in my table
undefined
undefined
I changed your json into following format :
{
"provinces" :[
{ "province":"Western", "name":"Colombo" },
{ "province":"Western", "name":"Gampaha" },
{ "province":"Western", "name":"Kalutara"}
]
}
You can validate your json with an online service such as https://jsonlint.com/
And your loop as follows :
for (x in myObj.provinces) {
txt += "<tr><td>" + myObj.provinces[x].name + "</td></tr>";
}
Replae below Code use x.name instead of myObj[x].name
function change_myselect(sel) {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: sel, limit: 20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + x.name + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "districts.json", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
JSON File must be like
[{
"name":"Colombo"
},
{
"name":"Gampaha"
}]

how to make more efficient js for loop inside php while loop JSON

I'm selecting values from my db in mysql and comparing them with values from JSON. I'm receiving the right results but since I'm using append the results shows up one by one, which looks like animation I would like to get them all at once and show some kind of loading icon while the loop is running, I've tried few different ways but nothing worked.
<?php $sql= "select a_id,b_id,res_a,res_b from betts_gr where u_id='".$u_id[0]."'";
$user_bets = mysqli_query($conn,$sql);
while($user_bets1 = mysqli_fetch_array($user_bets)){
?>
<script>
$(document).ready(function() {
var a_id = "<?php echo $user_bets1[0]?>";
.....
var car = [];
$.getJSON('http://api.football-api.com/2.0/matches?
comp_id = 1204 & from_date = '+today+' & to_date = '+plusmonth+' & Authorization ',
function(data) {
var html = "";
console.log(data);
$.each(data, function(index, value) {
var teama = value.localteam_name;
var teamb = value.visitorteam_name;
.......
function add(name, point) {
car.push({
teamb: teamb,
teama: teama,
form: form,
data: data,
teama_id: teama_id,
teamb_id: teamb_id,
a_res: a_res,
b_res: b_res
});
}
add(teama, teamb, data, form, teama_id, teamb_id, a_res, b_res);
});
for (var n = 0; n < car.length; n++) {
if (car[n].teama_id == a_id && car[n].teamb_id == b_id) {
html += "<tr><td><input type='hidden' name='aid" + n + "'
value = '"+car[n].teama_id+"' > < input type = 'hidden'
name = 'bid"+n+"'
value = '"+car[n].teamb_id+"' > " +
car[n].data +
"</td><td> " + car[n].teama + "</td><td>" + car[n].a_res + "-" +
car[n].b_res + "</td><td> " +
car[n].teamb + '</td><td> you predicted ->' + pred_resa + ' - ' + pred_resb +
'</tr>';
}
}
$(".message").append(html);
});
});
</script>
<?php } ?>
the example for using the Array.map and the template literals instead of the for loop and the plain string concat:
const isTargetTeam = item => item.teama_id == a_id && item.teamb_id == b_id;
const html = car.slice(0) // copy the array car
.filter(isTargetTeam)
.map((item, index) =>
`<tr>
<td>
<input type='hidden' name='aid${index}' value='${item.teama_id}'>
<input type='hidden' name='bid${index}' value='${item.teamb_id}'>
${item.data}
</td>
<td>
${item.a_res}-${item.b_res}
</td>
<td>
${item.teamb}
</td>
<td> you predicted -> ${pred_resa} - ${pred_resb}
</tr>`
).join('')
You should not mix PHP and Javascript like that. Currently this will result in X document.ready functions with X getJSON requests.
If you want to do the API requests from the local client, you should do ONE javascript function where you pass in the selected user_bets as an array. There are different possibilities to determine if all loadings have been finished: either counting up and checking after every callback if the max number is reached, or using Promises and Promise.all().
<script>
var user_bets = <?php echo json_encode($user_bets);?>;
$(document).ready(function () {
Promise.all(user_bets.map(function (id) {
return fetchFromApi(id);
})).then(function(array){
var html = "";
for(var i = 0; i < array.length; i++){
html += processData(array[i]);
}
$(".message").append(html);
});
});
function fetchFromApi(user_id) {
return new Promise(function (resolve, reject) {
$.getJSON()
.done(function (data) {
resolve(data);
})
.fail(function (error) {
reject(error);
});
});
}
function processData(data){
var html = '';
// do your html processing of a single api call here
return html;
}
</script>
Alternatively you can use CURL to do the API requests server-side already.
Thanks for advise I just realize I should get data with one request. I've passed the whole array to js and since I'm not sure how promise.all is working I did two for loops nested and is working fine, the only thing I still can't figure out how to check if the loops are finished so I could add loading icon while loop is running.
function add(name, point) {
car.push({ teamb : teamb, teama : teama, form:form, data:data, teama_id:teama_id,
teamb_id:teamb_id, a_res:a_res, b_res:b_res});
}
add(teama,teamb,data,form,teama_id,teamb_id,a_res,b_res);
});
for(var n=0;n<car.length;n++){
var taba = [<?php echo json_encode($at1)?>];
var tchild = taba[0];
for(var u=0;u<tchild.length;u++){
if(car[n].teama_id == tchild[u].localteam_id
&& car[n].teamb_id == tchild[u].visitorteam_id){
html += "<tr><td><input type='hidden' name='aid"+n+"'
value='"+car[n].teama_id+"'>
<input type='hidden' name='bid"+n+"'
value='"+car[n].teamb_id+"'>"
+car[n].data
+"</td><td> "+car[n].teama + "</td><td>"+ car[n].a_res
+ "-"+ car[n].b_res + "</td><td> "
+ car[n].teamb + '</td><td> you predicted -
>'+tchild[u].localteam_score +' - '+tchild[u].visitorteam_score +
'</td></tr>';
}
}
}
$(".message").append(html);

Displaying data stored in HTML session storage into page

I am trying to create a checkout page to send a confirmation to the customer of the products they want to buy. However, I am having trouble to display the data stored in the session storage into my checkout page. Whenever I click on the checkout button, the page only displays the title, and it doesn't display the data. Can somebody help me figure out this problem. I would really appreciate it.
HTML
<div id="show_checkout">
<h1 id="basket_header">- My Basket -</h1>
<!-- The items the user wants to buy, will be displayed on this table -->
<table id="basket_list"></table>
<!-- Displays the checkout and empty buttons -->
<div id="basketDiv"></div>
</div>
JavaScript
window.onload = loadBasket;
//Displays basket in page.
function loadBasket() {
//Get basket from local storage or create one if it does not exist
var basketArray;
if (sessionStorage.basket === undefined || sessionStorage.basket === "") {
basketArray = [];
} else {
basketArray = JSON.parse(sessionStorage.basket);
}
var tableBody;
var tableHeader = "<tr><th>Product Image</th><th>Product Name</th><th>Price</th></tr>\n";
//Build string with basket HTML
var htmlStr = "<p class='basket_items'>Number of items in basket: " + "<span style='color:red'>" + basketArray.length + "</span>" + "</p>";
var prodIDs = [];
for (var i = 0; i < basketArray.length; ++i) {
tableBody += "<tr><td>" + "<img class='basket_img' src='" + basketArray[i].image + "'>" + "</td><td>" + basketArray[i].name + "</td><td>£" + basketArray[i].price + "</td></tr>";
prodIDs.push({
id: basketArray[i].id,
count: 1
}); //Add to product array
}
//Add hidden field to form that contains stringified version of product ids.
htmlStr += "<input type='hidden' name='prodIDs' value='" + JSON.stringify(prodIDs) + "'>";
//Add checkout and empty basket buttons
htmlStr += "<input class='checkout_button' onclick='checkoutBasket()' type='submit' value='Checkout'>";
htmlStr += "<button class='empty_basket' onclick='emptyBasket()'>Empty Basket</button>";
//Display number of products in basket
document.getElementById("basketDiv").innerHTML = htmlStr;
document.getElementById("basket_list").innerHTML = tableHeader + tableBody;
}
//Deletes all products from basket
function emptyBasket() {
sessionStorage.clear();
loadBasket();
}
function checkoutBasket() {
// Create request object
var request = new XMLHttpRequest();
// Create event handler that specifies what should happen when server responds
request.onload = function() {
// Check HTTP status code
if (request.status == 200) {
var responseData = request.responseText;
document.getElementById("show_checkout").innerHTML = responseData;
} else
alert("Error communicating with server: " + request.status);
}
// Set up request with HTTP method and URL
request.open("POST", "php/checkout.php");
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Send request
request.send();
}
PHP
<?php
//Extract the product IDs that were sent to the server
$prodIDs = filter_input(INPUT_POST, 'prodIDs', FILTER_SANITIZE_STRING);
//Convert JSON string to PHP array
$productArray = json_decode($prodIDs, true);
//Output the IDs of the products that the customer has ordered
echo '<h1 id="basket_header">- My Order -</h1>';
for($i=0; $i<count($productArray); $i++) {
echo '<p>Product ID: ' . $productArray[$i]['id'] . '. Count: ' .
$productArray[$i]['count'] . '</p>';
}
?>

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

Getting an image source from JSON data

I'm attempting to call a PHP file and have it return a result (a single record's 'pageLocation') from a database table ('page'). I then want to get that result into a variable, so I can use it while creating an image in html.
Currently, the image is being created but the source is not feeding into it, leaving a default empty image at the correct size.
Javascript:
// Loads a list of comics created by the user from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Non-relevant code affecting layout if no comics are found.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
// Gets image source from database.
imgSrc = "";
tempID = arr[i].comicID;
$.post("getCover.php", {'comicID':tempID}, function(result)
{
imgSrc += ("" + result);
}
);
// Creates image item and associated radio button.
out += "<hr><br><img name = '" + ('com' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + imgSrc + "'><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT FIRST (pageLocation) FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$conn->close();
echo ($result);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
Thanks for any help provided.
You need to get he data from the result, like:
$row = $result->fetch_assoc()
Also, yes, Jim G is right, you need to escape that POST variable.

Categories

Resources