How to display certain JSON elements in HTML? - javascript

I would like to display the variable "hashrate" from this JSON file on a HTML webpage. I have looked around the internet, but many of the methods have not worked. Sorry if this is a duplicate question, I am very lost.

var json = {"getpoolstatus":{"version":"1.0.0","runtime":19.948959350586,"data":{"pool_name":"Capy's Pool - Gabencoin","hashrate":5.8254222222222,"efficiency":0,"workers":0,"currentnetworkblock":21903,"nextnetworkblock":21904,"lastblock":21903,"networkdiff":0.0392466,"esttime":28935.733248,"estshares":2572,"timesincelast":189,"nethashrate":451133}}};
your variable - json.getpoolstatus.data.hashrate

var xhr = new XMLHttpRequest(); //Request the data
xhr.open('POST','http://gaben.capyspool.co.uk/gabencoin/public/index.php?page=api&action=getpoolstatus&api_key=72f3fd60d9a536215a6f6f92938592a60f919586635d7d0dedcf6a394888c435',true);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState === 4) { //When it's ready
var data = JSON.parse(this.responseText); //Parse the data
alert(data.getpoolstatus.data.hashrate); //And here it is!
}
}

Related

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};

Updating javascript array variable through javascript ajax?

I have a javascript variable that holds an array to update a map and I am trying to get AJAX to update that variable with the server data so that it will update the map based on a selected option.
Basically, here is where I'm at
Javascript:
var mapData=[];
function stateData(inputData){
data = [inputData];
return data;
}
AJAX:
function updateData(selectedVar){
var newRequest = new XMLHttpRequest();
newRequest.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
serverdata = this.responseText;
mapData = serverdata;
stateData(mapData);
}
};
newRequest.open("GET", "testscript.php?selection="+selectedVar, true);
newRequest.send();
}
If it helps the data that I'm transferring is in this format after PHP script:
{state="AK", hourlypay=18.22, annualpay="43,666"}, {state="AZ", hourlypay=25.88, annualpay="89,980"}, etc.

Properly passing information to a prototype

Only using javascript.
I want to create a prototype called Table that gets all table values such the array that contains all information, how many rows are going to be displayed, the default rows that are going to be displayed, etc.
With AJAX i'm getting the query and parsing to json, then giving to loadTable the jsonArrayList so I can dynamically create the table depending on how many rows the user want to be displayed.
I am not able to give to the prototype the Array (jsonObj.aaData), i guess is not in the scope and ends being undefined, how do i do it correctly?
function loadQuery() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//parse to JSON, sends arrayList to loadTable
var jsonObj = JSON.parse(xhttp.responseText);
// function to create the table
//loadTable(jsonObj.aaData);
//does not work
var table_info = new Table(jsonObj.aaData);
}
};
display_number = refreshDropdown();
xhttp.open("GET", "server_processing2.php?iDisplayStart=1&iDisplayLength=" + display_number, true);
xhttp.send();
}
The thing is creating an instance that all functions can see and extract the information from that instance instead of passing parameters from one function to another.
function Table(jsonArrayL){
this.jsonArrayL = jsonArrayL;
this.default_rows = 25;
}

Javascript / REST / Activiti - What am I doing wrong in my XMLHttpRequest?

I'm trying to learn how to use the Activiti REST api and I'm have trouble getting back data. I'm not very familiar with using rest apis so I may be making a stupid mistake, but as it stands I can't figure it out.
I've had success getting back JSON using the Advanced REST Client for Chrome but I can't seem to implement it with Javascript.
I'd really appreciate it if someone could point me in the right direction. Links to relevant tutorials and videos would also be much appreciated.
window.onload = function get_json() {
var hr = new XMLHttpRequest();
var url = "http://kermit:kermit#localhost:8080/activiti-rest/service/repository/process-definitions";
var result = document.getElementById("result");
hr.open("GET", url, true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readystate == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
result.innerHTML = data;
}
}
hr.send();
}
Two problems. The main is that it's readyState, not readystate. So it should be
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
result.innerHTML = data;
}
}
The second problem is that you probably don't want to just assign object to innerHTML because it will be meaningless [object Object]. But rendering of the data is beyond this question.

JSON Parse File Path

I'm stuck trying to get the correct path to the local file. I have the following directories:
Resources ->
data ->
file.json
js ->
folder ->
script.js
html ->
folder ->
file1.html
I'm executing script.js from file1.html, with js code:
var answers = JSON.parse('../../data/file.json');
alert(answers);
But it doesn't work, even alert is not starting.
What is wrong?
Also I've tried this:
function readJSON(file) {
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
if (request.status == 200)
return request.responseText;
};
var temp = readJSON('../../data/file.json');
alert(temp);
Alert undefined in this case.
Since it is in the directory data/, You need to do:
file path is '../../data/file.json'
$.getJSON('../../data/file.json', function(data) {
alert(data);
});
Pure JS:
var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
alert (my_JSON_object.result[0]);
This solution uses an Asynchronous call. It will likely work better than a synchronous solution.
var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null);
request.onreadystatechange = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var my_JSON_object = JSON.parse(request.responseText);
console.log(my_JSON_object);
}
}
Loading local JSON file
Use something like this
$.getJSON("../../data/file.json", function(json) {
console.log(json); // this will show the info in firebug console
alert(json);
});
var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);
This code worked for me.
If Resources is the root path, best way to access file.json would be via /data/file.json
My case of working code is:
var request = new XMLHttpRequest();
request.open("GET", "<path_to_file>", false);
request.overrideMimeType("application/json");
request.send(null);
var jsonData = JSON.parse(request.responseText);
console.log(jsonData);
Even if long time answerd, I here is another that does not need to create a request. I created a lg.js script containing a class and some functions (setLg, de, en, ...)
Each "lg" function (de, en, fr, ...) provides a json object containing the translations.
"use strict"
class Lg {
constructor() { this.tr = this.en(); }
setLg(l) {
if l == "de" this.tr = this.de();
if l == "en" this.tr = this.en();
de() {
"item": "Artikel",
"login": "Login"
}
en() {
"item": "Item",
"login": "login"
}
}
var lg = new Lg(); //global accessable object
You can then use it by "lg.tr.item"
You could also create a small function, that checks if the "key" is in the JSON object to have some kind of error checking.

Categories

Resources