I am trying to get JSON data from REST displaying on a web page using javascript
I have the following REST call working fine to the firefox console
function gethosts() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://10.10.10.10/api/machine", false);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var response = JSON.parse(xhttp.responseText);
}
The JSON data is the following,
{
"offset": 0,
"hosts": [
{
"id": "422022c0-4ca7-66a2-bf73-9b56a65c9d2f",
"name": "System Z",
"type": "ORIGINAL",
"model": "System X",
"version": "Release 01",
"management_ip": "10.10.10.11",
"state": "ALIVE",
"date": "2017-01-05T17:55:58Z"
},
I want this displayed using html
Name: System Z
Model: System X
Version: Release 01
MGMT IP: 10.10.10.11
State: ALIVE
I tried adding this to the function but it doesn't seem to work
obj.hosts[0].name// return name
obj.hosts[0].model // return model
$( "body" ).append("<div>"+obj.hosts[0].name+"</div>")
$( "body" ).append("<div>"+obj.hosts[0].model+"</div>")
The sample HTML code is,
<button type="button" onclick="gethosts()">Get all Hosts</button>
<div id="gethosts">Hosts: </div>
Where did obj come from? response is the parsed JSON.
function gethosts() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://10.10.10.10/api/machine", false);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var response = JSON.parse(xhttp.responseText);
$("body").append("<div>"+response.hosts[0].name+"</div>")
$("body").append("<div>"+response.hosts[0].model+"</div>")
}
Also, why the mix of vanilla JS and jQuery? Why not use $.ajax if you already have jQuery loaded?
Related
I have a basic XML request that gets data from a json file stored on my server. Once the request is loaded a function is called that stores the responseText in a variable called data. Once the data is stored, it is then parsed using JSON.parse and stored into a variable called workouts.
Here is my js code:
var data;
var workouts;
var req = new XMLHttpRequest();
req.open("GET", "workout-db.json");
req.onload = function() {
data = req.responseText;
workouts = JSON.parse(data);
}
req.send();
Here is my json code:
[{
"name": "Pull up",
"muscleGroup": "upper",
"imgUrl": "imgs/pull_up.jpg"
},
{
"name": "Battle rope",
"muscleGroup": "upper",
"imgUrl": "imgs/battle_rope.jpg"
},
{
"name": "Push up",
"muscleGroup": "upper",
"imgUrl": "imgs/push_up.jpg"
}
]
Only part I don't understand is how to access this workout object in my code. Trying to call it returns an undefined variable. From what I understand about js scope, the workouts variable should be global and accessible anywhere else in my code.
I have a list of data in my JSON file. I am trying to output certain strings and arrays from my JSON file via my JS. How do I go on about this? All these files are saved on my desktop.
I've tried Xhttp code. But I think I need some server going on for that, and I don't have that. Also, I'm pretty sure this should be possible without having to use a server?
PS: the json file is named: movie.json
JSON CODE
{
"movie": {
"name": "drive",
"year": "2011",
"people": {
"actors": [
{
"name": "ryan gosling"
},
{
"name": "cary mulligan"
},
{
"name": "bryan cranston"
}
]
}
}
}
JS CODE
function preload() {
var movie = load.JSON("movie.json");
}
function(movie) {
var movie = JSON.parse(movie);
console.log(movie[0].name);
console.log(movie[0].year);
console.log(movie[0].actors);
}();
drive, 2011, ryan gosling, cary mulligan, bryan cranston
var movie;
var http = new XMLHttpRequest();
xhhtp.open( "GET", "movie.json", true);
xhttp.onreadystatechange = function () {
if(http.readyState == 4 && http.status == 200) {
movie = JSON.parse(http.responseText);
}
}
http.send();
console.log(movie[0].name);
console.log(movie[0].year);
console.log(movie[0].actors);
I do not know if the code above will help you. Using XMLHttpRequest will help you fetch the json file then you can parse and sort into array. Note: you do not need a server to use XMLHttpRequest, if you have text editor like VSCode you can us it to run live HTML codes then you can get the full link to the JSON file you want to parse e.g localhost:9000/movie.json
I am trying to create a table using DataTable but having a hard time getting DataTable to load with JSON object.
function getData() {
var request = new XMLHttpRequest();
var json = "link-to-my-json-object";
// Get JSON file
request.onload = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var JSONObject = JSON.parse(request.responseText);
createTable(JSONObject);
} else if(request.status == 400) { console.log("Error", request.status);}
};
request.open("GET", json, true);
request.send();
}
Requesting the JSON file via a XMLHttpRequest() request.
short sample of the JSON object:
{
"meta": {
"version": 1,
"type": "test"
},
"reports": [
{
"report-metadata": {
"timestamp": 1528235303.721987,
"from-ip": "0.0.0.0"
},
//and so on...
Currently only trying to show the meta part in a DataTable table:
function createTable(jsonData){
$(document).ready(function(){
$('#table').dataTable({
data: jsonData,
columns: [
{ data: 'meta.type' },
{ data: 'meta.version' }
]
});
});
}
index.html part:
<table id="table" class="display" style="width:100%"></table>
Only getting a No data available in table when running, and I am obviously missing something.
The "data" attribute for initializing your Data Table is expecting a list (Each element representing a row). Modify your ajax response, so each row is an element in the jsonData list. I also added quotes around all the JSON options.
var jsonData = [
{ "meta": { "version": 1, "type": "test" } }
];
$('#table').DataTable({
"data": jsonData,
"columns": [
{ "data": "meta.type" },
{ "data": "meta.version" }
]
});
https://datatables.net/reference/option/data
Since you want to load your data via ajax, you should look at the ajax options built in to the DataTables API. https://datatables.net/manual/ajax
I am looking to get the links on this WikiQuote page. I would like to see what subcategories exist under the 'Fundamental' category. They appear as links on the page, so it seemed natural to ask the API for the links. I only get back the "Category schemes" and "Main page" links, which exist in the introduction. What am I doing wrong/what have I misunderstood here?
CODE
function httpGetAsync(theUrl, callback){
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
callback(xmlHttp.responseText);
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send('null');
}
function callback(json_response){
stuff = json_response;
console.log(JSON.stringify(JSON.parse(json_response), null, 2));
}
httpGetAsync('http://en.wikiquote.org/w/api.php?action=query&prop=links&titles=Category:Fundamental&origin=*&format=json', callback);
Output
{
"batchcomplete": "",
"query": {
"pages": {
"4480": {
"pageid": 4480,
"ns": 14,
"title": "Category:Fundamental",
"links": [
{
"ns": 4,
"title": "Wikiquote:Category schemes"
},
{
"ns": 14,
"title": "Category:Main page"
}
]
}
}
}
}
Solution
httpGetAsync('https://en.wikiquote.org/w/api.php?&action=query&list=categorymembers&cmtitle=Category:Fundamental&cmtype=subcat&origin=*&format=json', callback);
API documentation for the query used in the solution.
Explanation
This is asking for the first 10 (cmlimit not specified, so it defaults to 10 returned items) subcategories on from the Fundamental category page.
The solution addresses the issue by returning the subcategories I was after, it is not asking for the links. I am not sure why they are not appearing as links but it does get me to the end result I was after anyway.
Credits
Thanks to randelldawson on the FreeCodeCamp forums for this solution.
I use the SMILES timeline loading event data as JSON from file and as variable.
Loading from file works fine using the samplecode from the homepage:
tl = Timeline.create(document.getElementById("div-timeline"), bandInfos);
Timeline.loadJSON("js/timelinedata.json", function(json, url) {
eventSource.loadJSON(json, url); });
Here is the content of my file timelinedata.json:
{"dateTimeFormat": "iso8601",
"events" : [
{"start": "1924",
"title": "Barfusserkirche",
"description": "by Lyonel Feininger, American/German Painter, 1871-1956",
"image": "link to an image",
"link": "link to an article"
}
]}
However when i paste the JSON into a var and try to load it i get complains.
This is how i populate my var:
function TimeTestData1(){
var TimelineEvent = {"dateTimeFormat": "iso8601",
"events" : [
{"start": "1924",
"title": "Barfusserkirche",
"description": "by Lyonel Feininger, American/German Painter, 1871-1956",
"image": "link to an image",
"link": "link to an article"
}
]};
return TimelineEvent;
}
And use it in timeline:
var tdata = TimeTestData1();
console.dir(tdata); // this looks fine
// [ timeline code ]
Timeline.loadJSON(tdata, function(json, url) { eventSource.loadJSON(json, url); });
I get an "alert" popup with the message:
Failed to load json data from [object Object] Not Found
When i use JSON.stringify(tdata) like this:
Timeline.loadJSON(JSON.stringify(tdata), function(json, url) {
eventSource.loadJSON(json, url); });
The browser tells me (using alert popup):
Failed to load json data from {"dateTimeFormat":"iso8601","events":[{"start":1924,"title":"Barfusserkirche","description":"by Lyonel Feininger, American/German Painter, 1871-1956","image":"link to an image","link":"link to an article"}]}
Not Found
here is the complete code of the timeline function:
function LoadTimeline() {
var tl;
var eventSource = new Timeline.DefaultEventSource(0);
//var tdata = TimeTestData1();
var theme = Timeline.ClassicTheme.create();
theme.timeline_start = new Date(Date.UTC(1890, 0, 1));
theme.timeline_stop = new Date(Date.UTC(2020, 0, 1));
var d = Timeline.DateTime.parseGregorianDateTime("1950") // set date to display
var bandInfos = [
Timeline.createBandInfo({
width: "70%",
intervalUnit: Timeline.DateTime.YEAR,
intervalPixels: 100,
eventSource: eventSource,
date: d
}),
Timeline.createBandInfo({
width: "30%",
intervalUnit: Timeline.DateTime.CENTURY,
eventSource: eventSource,
date: d,
intervalPixels: 200
})
];
bandInfos[1].syncWith = 0;
bandInfos[1].highlight = true;
tl = Timeline.create(document.getElementById("div-timeline"), bandInfos);
Timeline.loadJSON("js/timelinedata.json", function(json, url) {
eventSource.loadJSON(json, url); });
} //JSON.stringify(tdata) or tdata or "js/timelinedata.json"
How do I have to pass my event json var so timeline eats it?
Timeline.loadJSON expects a URL, not JSON. Try removing that call altogether and only call eventSource.loadJSON(tdata, url); instead. (not sure what the url-parameter is for in this case, documentation looks really bad for this project)
Not sure if anyone will see this but loadJSON() is expecting a JSON object as the first parameter, and not a string (which is what you are doing by saying JSON.stringify()). So as long as tdata is a JSON object compatible with Timeline, then all you need to do is
eventSource.loadJSON(tdata, window.location.href)