Printing JSON object data to HTML - javascript

I am trying to write an html code that shows current version of my software product (something like "v1.0.0") with printing data from a JSON file.
In my server there is a JSON file that stores the my software product version data like below (let's say the location is https://testsite.com/myproductversion.json):
{
"Name": "MyProduct",
"MajorVersion": "1",
"MinorVersion" : "0",
"MaintenanceVersion" : "0"
}
Is it possible? Any help would be appreciated.

fetch('/myproductversion.json').then(res => res.json())
.then(({ MajorVersion, MinorVersion, MaintenanceVersion }) => {
let version = `v${MajorVersion}.${MinorVersion}.${MaintenanceVersion}`;
$('.my-version-goes-here').html(version);
}).catch(console.error);
Just use fetch to make a request for the data.

i hope i understand your question right.
One of many ways is to use jquery/js.
Here is a small snippet to give you an example
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

Related

URL in JSON return as undefined

I'm trying to loop through some JSON but once it gets to the values that are url's, they are returning as undefined. Here's a simplified example of my JS
$.getJSON("https:../houston-locations.js", function(data){
$.each(data, function(i, data){
$("ul.mapList").append(
'<li id="store-' + data.restaurant + '">'+
'<div class="singleLocation">' +
'<button class="directions">DIRECTIONS</button>' +
'Restaurant Details' +
'</div>' +
'</div></li>'
)
})
});
And my JSON:
{ "restaurant":31, "restaurantName":"Shenandoah", "address":"19075 IH 45 S Suite 480", "city":"Shenandoah", "state":"TX", "zip":77385, "phone":"(936) 271-9217", "directions":"https://www.google.com/maps/dir//Pei+Wei,+19075+I-45+%23480,+Shenandoah,+TX+77385/#30.1826863,-95.4533763,17z/", "url":"/texas/31-shenandoah"}
The two keys at the end, "directions" and "url" are the only ones that return as undefined. What am I doing wrong?
Problem is here:
$.getJSON("https:../houston-locations.js", function(data){
$.each(data, function(i, data) {
You are overwriting variable data in function(i, data), consider to change it to value or something else.
Use this code:
$.getJSON( "ajax/ejemplo.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "" + val + "" );
});
$( "", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
$.getJSON("https:../houston-locations.js",function(data){
console.log(data);
$.each(data, function( key, value ){
console.log(data.directions);
console.log(data.url);
});
});
the right use of $.getSOn is as above
I found the solution to be something so simple.. It was a cache issue so the new JSON data wasn't being loaded. I did however change the overwriting 'data' values. Thanks everyone!

Error with using PHP File in javascript

I have the following problem. I have a PHP File, which should give me a JSON Object so I can display it in my HTML File. This works perfectly, I receive a output, which looks like a JSON Object, but although I will post the PHP File here:
<?php
header('Content-Type: application/json');
$erg = array (
"London" => array(
"Wetter" => "Regnerisch",
"Grad" => 12
),
"Manchester" => array(
"Wetter" =>"Sonnig",
"Grad" => 15
),
"Cambridge" => array(
"Wetter" => "Bewoelkt",
"Grad" => 5
)
);
echo json_encode($erg, JSON_PRETTY_PRINT);
?>
I have read something about $.ajax, but I donĀ“t know if I can use it like this:
$(document).ready(function() {
var newHtml;
$.ajax({
url: 'Server2.php',
type: 'get',
cache:false,
success: function(json) {
$.each(json,function(i, item) {
newHtml += '<div>' + item.Wetter + '</div>'
})
$('#inhalt').html(newHtml);
}
});
});
But when I try to display it in the browser, I receive the following error:
So I want just to display the output of the PHP File in a div, which I insert into my div with the id inhalt in my HTML document.
I appreciate every help from you guys.
Just tested this code. Try this code for the jQuery part:
$(document).ready(function() {
var newHtml;
$.ajax({
type: 'GET',
dataType: 'json',
url: 'Server2.php',
complete: function( json ){
//$.each( json.responseJSON, function(i, item) {
// newHtml += '<div>' + item.Wetter + '</div>'
//});
// Try this for the keys
for(var key in json.responseJSON) {
newHtml += '<div>' + key + '</div>'
}
$( '#inhalt' ).html( newHtml );
}
});
});
More Info
if you want to get the key and the Wetter key for each location then try this
for(var key in json.responseJSON ) {
var wetter = json.responseJSON[ key ].Wetter,
grad = json.responseJSON[ key ].Grad;
// You can now use the wetter and grad vars wherever you want inside this function
newHtml += '<div>' + key + '</div>'
}
I see that the ajax response contains the entire PHP file, this means there could one of the two possible issues here -
It seems like you're not running the html file via apache. What's the URL in your browser? Does it start with file://C:/www/html/test.html, if so you should load that file via Apache, so should be something like http://localhost/test.html
Apache is not parsing PHP files, in which case you need the php module installed. You might want to install/enable the php module but since you said the response is being received, I'd say you have it installed.
Can you tell me what URL you are typing to access the html page in the browser? In addition please check the Network tab in Chrome to see the AJAX call in realtime.

Accessing key value pairs from ajax call with jQuery

I am using jquery to call for a Json object from the server. This is my call:
$.getJSON( url, function( data ) {...}
I am getting back (from console.log) the following object:
> 0: Object
cable key: "1"
cable type: "Building Wire..."
> 1: Object
cable key: "2"
cable type: "PVC Wire..."
...
I am trying to access both key and value like the examples below without any luck.
$.getJSON( url, function( data ) {
$.each( data, function( key, value ) {
$( "#CableType" ).append( $( "<option value='" + value['cable key'] + "'>" + value['cable type'] + "</option>" ) );
});
})
Thanks for any help
You are trying to get a property of the VALUE instead of the object. Use
data['cable key']
instead of
value['cable key']
Beside, adding elements to the DOM inside a loop is inefficient. You need to collect your html in a string, and after the loop ends, put it in the DOM. You can do something like this:
$.getJSON( url, function(data){
var htmlCollection = "",
propertyName;
data.forEach(function(pair){
htmlCollection += "<option value='" + pair['cable key'] + "'>" + pair['cable type'] + "</option>";
});
$( "#CableType" ).append(htmlCollection);
});

Converting HTML list from json files

I have a problem with my code when listing countries from json file:
My HTML
<div id="country">country</div>
My JS Code
$.getJSON( "country.js", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
html: items.join( "" )
}).appendTo( "#country" );
});
Fiddle link
You are missing a comma in your json source.
Find this line:
{"countrName" : "Virgin Islands, U.S.", "dialCode" : "+1 340", "countryCode" : "VI"}
Your json source is wrong.
remove var countryList =
Find code: 'TF' and change it to "code": "TF"
You accessed wrong variable.
items.push( "<li id='" + val.countryCode + "'>" + val.countrName + "</li>" );
There was a problem with your generated json, I fixed that one and updated file will be found here
Whats make your file invalid is
For better understanding below is the code that I tested
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="country">country</div>
<script type="text/javascript">
$.getJSON( "country.json", function( data ) {
console.log(data);
var items = [];
$.each( data, function( key, row ) {
items.push( "<li id='" + row.countryCode + "'>" + row.countrName + "</li>" );
});
$( "<ul/>", {
html: items.join( "" )
}).appendTo( "#country" );
});
</script>
N.B: I changed each loop to make it working. Please look into that closely. Also if your country list comes dynamically from any script. Please make that error fixed for generated JSON
Good Luck
Another solution is remove var countryList = from your json file.
use json like a service anyone can use easily.
by writing var countryList this json will limited to javascript only.
Preferred solution is:
read file using $get
like
var items = [];
$.get("https://dl.dropboxusercontent.com/u/100011869/country.js", function(data) {
var gList = eval("(" + contryList + ")");
for (var i = 0; i < gList.length; i++) {
items.push("<li id='" + gList[i].countryCode + "'>" + gList[i].countrName + "</li>");
}
alert(items.join(""));
});

How to store JSON data from a file into an array of strings

I am working on Dynamic Web Project in Eclipse and using HTML 5 and Javascript as well.
I could manage to parse JSON file that is saved locally in my system though the code below:
$.getJSON( "/Users/Documents/workspace2/sample.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Let's suppose this is the JSON file:
{"resource":"A","literals":["B","C","D"]}
My question is: Is there any possibility to have an array of strings to store these elements that are inside the JSON file after parsing. I am quite new to jQuery and couldn't really manage to see these elements stored in an array of strings, for example. Could anyone help me with this issue please.
Try this way :
jsonFile.json
{
"resource":"A",
"literals":["B","C","D"]
}
myFile.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$.getJSON( "jsonFile.json", function( data ) {
var items = [];
$.each( data, function( key, val1 ) {
items.push( "<li><a href=#'" + key + "'>" + val1 +"</a></li>");
});
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
</script>
</head>
<body>
//result will be displayed here
</body>
</html>
Output :
var abc = JSON.stringify({"resource":"A","literals":["B","C","D"]});
var ab = JSON.parse(abc);
var arr=$.map(ab, function(value, index) {
return [value];
});
Hope it helps.

Categories