Cannot render json file data to html - javascript

I have a JSON file named colors.js and looks like this:
{
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0,0,0,1],
"hex": "#FFF"
}
},
]
}
Here is how I have handled the html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script type="primary" src="colors.json"></script>
<script type="text/javascript">
colorItems=['beige', 'red', 'blue'];
function loadJSON() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'colors.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
colorItems.push(JSON.parse(xobj.responseText)); // line 21
console.log(xobj.responseText); // line 22
}
};
}
function loadData(){
for (i=0; i<4; i++){
console.log(colorItems[i]);
document.getElementById('myP1').innerHTML+=colorItems[i]+'<br>';
}
}
</script>
<title></title>
</head>
<body onload="loadData()">
<p class="myP" id="myP1"></p>
<p class="myP" id="myP2"></p>
<p class="myP" id="myP3"></p>
<p class="myP" id="myP4"></p>
<p class="myP" id="myP5"></p>
</body>
</html>
I need when the page loads, information from each object (in the JSON file) be pushed to colorItems array. Then, they array renders to the paragraphs (that have class myP) in the body. However, I face two problems:
I am only able to get data to the paragraphs using getElementById, but
not getElementsByClassName .
I am not able to get the right data be pushed into colorItems array. Consequently, I am not able to get needed info on the html page.
This is how the output looks like (and how I need it to be):

You might want to take a look at this answer: Can I access variables from another file?
Firstly, you are not correctly receiving your .json because you are not even calling loadJSON(). Functions can be defined and called. What you did was just defining two functions and then calling the second one through the "onload" parameter. You forgot to call loadJSON(). In case you don't know how to do this, you have to write loadJSON() right inside loadData.
Seconly, even if you call that function, it won't work because you are not working on a server. Thus, as the question in the link above says, you'll get this error:
XMLHttpRequest cannot load file:///[path-to-file]. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Regarding your first question, you should take a different approach. With a loop, you should create as many p elements as elements has the final colors array. Take a look at this guide: https://www.w3schools.com/js/js_htmldom_nodes.asp,

I think the way to push colors (object) to colorItems (array) could be this:
colorsjs.colors.map((o,i)=>{
colorItems.push(o.color);
});
Then, in load data:
function loadData(){
for (i=0; i<colorItems.length; i++){
document.getElementById('myP'+(i+1)).innerHTML = colorItems[i]+'<br>';
}
}
Full example here https://jsfiddle.net/or9o9upb/
If you want to iterate over the class element:
var el = document.getElementsByClassName("myP");
for(let i = 0; i<el.length; i++){
el[i].innerHTML = colorItems[i];
}
Example here https://jsfiddle.net/8Lq2nd23/
If you have a js file with the json:
<script src="/path/to/colors.js"></script>
<script>
//it's already available
console.log(colorsjs);
</script>
But your js have to be something like this:
var colorsjs = {
"colors": [//....code

Related

Parse content from a html page

Need to dynamically update contents in a div of main page, based on data fetched from other html page
setInterval( function() {
$.ajax({
type:'GET',
url:"url for status",
success : function(data){
console.log(data);
}
})
},3000);
The content of 'data' printed in developer tool console is:
<html>
<style>
</style>
<head>
</head>
<script>
var conns=[{num:1,
id:1,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_1',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
},
{num:2,
id:2,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_2',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
}]
</script>
</html>
Need to extract the ConnectionStatus, Name and ConnectionError from this content and display it in respective div in main page.
I would recommend using a different transfer type, however, you could use something like this:
function break_out_each_id(){//returns array of indexes where id starts
var i = 0;
id_objs = [];
while data.indexOf('id', i) > -1{
id_objs[i] = data.indexOf('id', i);
i++;
}
return id_objs
}
function find_values(){//pseudo code
use the array of indexes from first index to next index
in that string, do index of each value you are looking for (ConnectionStatus...)
then parse that line after the ':' to get the value.
Do this for each index in indexes array
}
Sorry for the pseudo code, but this post is getting really long. Like I said, it would be MUCH better to just send the response as JSON (even if it is a stringified version of it). In that case you could just do a simple JSON.parse() and you'd be done.

How to convert Google PageSpeed Insight JSON results to HTML

I have never worked with JSON before and I am stuck at converting my results to html. I would like them to spit out as ul's and li's preferably. I have tried plugins and Jquery scripts but nothing seems to work. My assumption is that the way I am spitting out the results is incorrect, but as I said I have no idea what I am doing with server response objects.
HTML:
<input type="text" placeholder="Enter webpage URL e.g.http://www.domain.com" id="url"/>
<input type="button" id="button" value="PageSpeed Data" onclick="clicked();" />
<div id="urlerror">Please Enter a Valid URL e.g. http://www.domain.com</div>
<pre id="data"></pre>
My code to get the results:
<script>
function clicked()
{
document.getElementById("urlerror").style.display = 'none';
var xhr = new XMLHttpRequest();
var url = document.getElementById("url").value;
if(url.indexOf('http://') === -1){document.getElementById("urlerror").style.display = 'block'; return;}
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url="+encodeURIComponent(url)+"&key=AIzaSyAIOUFcLYeo2WN1qbPSjlMbXmLi8kmOacw&strategy=mobile");
xhr.onload = function(){
document.getElementById("data").innerHTML = xhr.responseText;
}
xhr.send();
}
</script>
The resulting short snippet JSON object example (not full code):
{
"kind": "pagespeedonline#result",
"id": "http://www.celebritynewsdaily.us/",
"responseCode": 200,
"title": "Celebrity News Daily | Your Daily Source for Celebrity News & Updates",
"score": 64,
"pageStats": {
"numberResources": 71,
"numberHosts": 13,
"totalRequestBytes": "11777",
"numberStaticResources": 35,
"htmlResponseBytes": "235467",
"textResponseBytes": "238",
"cssResponseBytes": "135950",
"imageResponseBytes": "545748",
"javascriptResponseBytes": "762058",
"otherResponseBytes": "107518",
"numberJsResources": 13,
"numberCssResources": 11
},
"formattedResults": {
"locale": "en_US",
"ruleResults": {
"AvoidInterstitials": {
"localizedRuleName": "Avoid app install interstitials that hide content",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "Your page does not appear to have any app install interstitials that hide a significant amount of content. Learn more about the importance of avoiding the use of app install interstitials.",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/webmasters/mobile-sites/mobile-seo/common-mistakes/avoid-interstitials"
}
]
}
}
]
}
}
Any help getting this working is greatly appreciated.
Once you've got the JSON string, it is easy to convert into a JavaScript object by calling JSON.parse().
var myObject = JSON.parse(jsonString);
Once you've got the object, you can reference values within it as per a normal JS object; eg myObject.pageStats.numberResources, and use the DOM methods to insert them into DOM elements.

Display using template-node in node red(IBM BLUEMIX)

I was trying to get a run-time value(msg.payload) from a function node(node-red) and supply it to a template node(node-red) to display appropriate image according to the input.I used the below code,but the image is not changing according to the choice of input. Below is the code. Please take a look and provide me some insights or what needs to be changed to make it work.
<html>
<head>
<script type="text/javascript">
function displayImage() {
var j=parseInt({{payload}});
document.getElementById("img").src = images[j];
}
function startTimer() {
setInterval(displayImage,3000);
}
var images = [];
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload="startTimer()">
<img id="img" src="image1.jpg"/>
</body>
</html>
Use the console.log(message)and check:
the {{payload}} parameter should be an integer as you expected
the value of J parameter, after its assignment, should an integer between 0-2
You are dealing with NodeRED. The easiest way to learn about your payload parameter is to use a Debug node (the dark green one) and attach it to the same output as the template node. You then will very quickly see what it is made of. Most likely your payload is a JSON object. Something like this:
{ "name" : "Peter",
"color" : "Blue",
"image" : "2"
}
... or similar.
Then you just change that content in {{ }} to reflect the variable inside the JSON object that has the number you are interested in. Like:
{{payload.image}}
Double check your function node. If it doesn't end with a return statement (typically return msg) you simply won't have any input.

How to display a list of JSON objects onto html page

NOTE: Need to implement this without the use of jQuery or any other open source code.
Here is what I have
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Model</title>
<script src="js.js"></script>
</head>
<body>
<h1>Browse all our products below:</h1>
Name: <span id="name"></span><br>
Desc: <span id="desc"></span><br>
Cost: <span id="cost"></span><br>
Stock: <span id="stock"></span>
</body>
</html>
js.js is below
var getProducts = function(){
console.log("Getting Products...");
var success = function() {
var product = JSON.parse(xhr.responseText);
console.log(product);
document.getElementById("name").innerHTML = product.name;
document.getElementById("desc").innerHTML = product.desc;
document.getElementById("cost").innerHTML = product.cost;
document.getElementById("stock").innerHTML = product.stock;
}
};
xhr = new XMLHttpRequest();
xhr.open("GET", "back.php");
xhr.addEventListener("load", success);
xhr.send();
};
window.addEventListener("load", getProducts);
back.php returns the following from a database. They have been json_encoded:
{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"}
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"}
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"}
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"}
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}
I need to display these objects onto the html page. I know I need to implement a for loop however, no matter whatever I try, a parse error for JSON comes up.
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at
line 1 column 86 of the JSON data
var product = JSON.parse(xhr.responseText);
Would much appreciate it if someone could help me understand how to display all the JSON objects onto the html page.
Your JSON is invalid. You need to put the objects in an array, and separate them by commas.
[{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"},
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"},
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"},
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"},
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}]
Here is an example using open source project jinqJs
Also the example is using jQuery.
Fiddle Example
//data can also be a string to a url that returns JSON
jinqJs().from(data).select(function(row) {
$('#items')
.append($("<option></option>")
.attr("value",row.nam)
.text(row.desc));
}
);

Calling JSON file from URL in JavaScript

I am trying to read a JSON file from a webpage and display the route contained in the file over my map in OpenLayers. I found another example similar to mine, How to fetch JSON from a URL using JavaScript?, but I couldn't get it working.
I create the URL string containing as, for example, something like this:
http://router.project-osrm.org/viaroute?rebuild=1&loc=43.46711564169348,-3.880102031707764&loc=43.4669443349282,-3.862788677215576&output=json
This webpage should return a JSON file with all the points I have to follow to reach my end point. I know this works because I tried with this example:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Open Space Web-Map builder Code</title>
</head>
<body>
<div class="header-content">
[
<a class="result-link" onClick="document.location.href='http://router.project- osrm.org/viaroute? rebuild=1&loc=43.46711564169348,-3.880102031707764&loc=43.4669443349282,-3.862788677215576&output=json';">Generar ruta</a>
]
</div>
</body>
</html>​
And it returns a JSON file, as shown below. But if I try to use my page, it doesn't work. I have this function to read JSON file:
function pintarRutaCamion() {
capaRuta = new OpenLayers.Layer.Vector("capaRuta");
var style_green = {
strokeColor: "#00FF00",
strokeOpacity: 1,
strokeWidth: 6
};
var pointRuta = [];
alert(rutaCompleta); //show the complete url
JQ.getJSON(rutaCompleta, function(puntosRuta) {
alert(puntosRuta.route_geometry.length); //show size of returned json file
for (i = 0; i < puntosRuta.route_geometry.length; i++) {
coordenadas = new OpenLayers.LonLat(puntosRuta.route_geometry[i][1], puntosRuta.route_geometry[i][0]).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
pointruta.push(coordenadas);
}
});
//create a polyline feature from the array of points
var lineString = new OpenLayers.Geometry.LineString(pointRuta);
var lineFeature = new OpenLayers.Feature.Vector(lineString, null, style_green);
capaRuta.addFeatures([lineFeature]);
//add it to the map
map.addLayer(capaRuta);
}​
The JSON file should be something like this:
{"version": 0.3,
"status": 0,
"status_message": "Found route between points",
"route_geometry": [[43.46716, -3.87987],[43.46668, -3.87963],[43.46706, -3.87761],[43.46593, -3.87740],[43.46571, -3.87552],[43.46559, -3.87515],[43.46553, -3.87512],[43.46549, -3.87504],[43.46548, -3.87496],[43.46550, -3.87487],[43.46554, -3.87482],[43.46558, -3.87433],[43.46533, -3.87210],[43.46535, -3.87185],[43.46546, -3.87128],[43.46592, -3.86911],[43.46598, -3.86859],[43.46593, -3.86824],[43.46589, -3.86818],[43.46587, -3.86808],[43.46588, -3.86800],[43.46581, -3.86780],[43.46560, -3.86761],[43.46545, -3.86756],[43.46526, -3.86756],[43.46517, -3.86760],[43.46511, -3.86760],[43.46502, -3.86753],[43.46498, -3.86743],[43.46497, -3.86734],[43.46499, -3.86718],[43.46510, -3.86711],[43.46521, -3.86696],[43.46530, -3.86675],[43.46547, -3.86606],[43.46569, -3.86504],[43.46639, -3.86166],[43.46716, -3.86194],[43.46698, -3.86278]],
"route_instructions": [["10","",56,0,155,"56m","SE",203.5],["7","",167,1,242,"167m","E",281.06],["3","Calle Polvorín",126,2,182,"126m","S",189.18],["7","CA-231",185,3,131,"185m","E",262.42],["11-2","CA-231",536,10,350,"536m","E",277.7],["11-1","CA-231",82,20,52,"82m","E",250.51],["11-2","Calle del Somo",36,31,19,"36m","NE",310.15],["1","Calle de El Somo",426,33,236,"426m","E",285.81],["7","Calle de Antonio Nebrija",88,36,127,"88m","N",17.56],["7","Calle de Manuel Cacicedo",70,37,76,"70m","W",103.84],["15","",0,38,0,"","N",0.0]],
"route_summary": {"total_distance": 1890,
"total_time": 179,
"start_point": "",
"end_point": "Calle de Manuel Cacicedo"},
"via_points": [],
"hint_data": {"checksum": -1013584035,
"locations": ["xqyjHgAAAACbAAAAzwAAABj5Tb5MZ9s_XFNCAG0U-v9", "WVr_FtzAKgAzAQAAaAAAAK5H_5Np-ec_SlNCABob-v9"]},
"transactionId": "OSRM Routing Engine JSON Descriptor (v0.3)"}
But it is impossible to get inside that function. I don't know what happens. I tried writing document.location.href= as the other example in the URL string but this also fails. Can anyone suggest why this is not working?
Your url should be like this,
http://router.project-osrm.org/viaroute?rebuild=1&loc=43.46711564169348,-3.880102031707764&loc=43.4669443349282,-3.862788677215576&output=json
And It seems that doesn't suppport jsonp callback, so you cannot request with $.getJSON directly because of Cross-Origin Resource Sharing.
you should use a proxy to avoid this problem, for example you can use YQL
here is an example with your url

Categories

Resources