Use the free REST API: https://jsonplaceholder.typicode.com/ to get
100 albums. And display all the albums on the html page as:
UserId: value of userId from the object that came to you,
Id: Id value from the object that came to you,
Title: title value from the object that came to you
As a result, 100 different albums should be parsed on your page.
I tried to parse data and the data becomes a JavaScript object using JSON.parse() but data is showed in json format
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
const url = "https://jsonplaceholder.typicode.com/albums";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
</script>
It works fine if you add a <div id="demo"></div>:
function loadDoc() {
const xhttp = new XMLHttpRequest();
const url = "https://jsonplaceholder.typicode.com/albums";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
<div id="demo"></div>
Related
Im currently trying to parse JSON data from this api in JS but im not sure how to. As of right now when I press any buttons to give me the data, it prints the arrays out rather than the specific data I want. Ive tried to use the JSON Parse function to retrieve the specific data but it seems its not working. Any help would be greatly appreciated! URL to the API docs: https://www.balldontlie.io/#get-all-players
//Loads Player Data
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("players").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
var data = JSON.parse(xhttp.responseText);
console.log(data["last_name"])
xhttp.send();
}
//Loads Game Data
function loadGames() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("games").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/games", true);
xhttp.send();
}
//Loads Team Data
function loadTeams() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("teams").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/teams", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body style="background-color:peachpuff;" >
<center>NBA STATS</center>
<center><marquee behavior="scroll" direction="right" scrollamount="12.5">Data Extracted From BDL API</marquee></center>
<center> View API Docs </center>
<script src="main.js"></script>
<div id="players">
<button type="button" onclick="loadPlayers()">View Players</button>
</div>
<div id = "teams" >
<button type="button2" onclick="loadTeams()">View Teams</button>
</div>
<div id ="games">
<button type="button3" onclick="loadGames()">View Games</button>
<div>
</body>
</html>
You should parse JSON in xhttp.onreadystatechange, that's a callback when request data success.
For the players data as example, it is an object with data and meta, and the players is in data key which is an Array, so you need to loop inside the array to print the values that you needed.
Here's the example for loadPlayers(). You can apply the same concept to loadGames and loadTeams, please let me know if you still having questions.
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// parse JSON after response
var players = JSON.parse(this.responseText);
// get 'data' key inside response
var playersData = players.data;
// loop all the players
for (var player of playersData) {
// print last_name to the #players element
document.getElementById("players").innerHTML += "<br />" + player['last_name'];
}
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
xhttp.send();
}
In function loadPlayers()
data is an array not object
I have been trying to read a JSON file from google cloud storage from my HTML
but he didn't work.
This is my json context:{'first_name': 'Anat'}
How can I get the context file?
This is my part of my html context:
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.first_name;
}
};
xmlhttp.open("GET", "https://storage.googleapis.com/{backetname}/{filename}.json", true);
xmlhttp.send();
</script>
I am working on a project using ESP32, I get some data from some sensors and send it to a webpage hosted in the same board.
I read some info on the web and understood that is "better" to send all data from several sensors using json method, so my function to get and send data is this:
void handle_leituras()
{
String results_json = "{ \"data\": " + Data +
"," + "\"hora\": " + Hora +
"," + "\"temp_amb1\": " + Tout + " }";
server.send(200, "application/json", results_json);
}
Testing above function in serial monitor I have this data:
{"data": Domingo, 12/4/2020,"hora": 20:53,"temp_amb1": 25.75}
I found a script that can get only one data and print it on that page, this is the script:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("DATA").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "leituras", true);
xhttp.send();
}
Its my index page code that shows data on webpage:
const char pag_inicial[] PROGMEM = R"=====(
<!DOCTYPE html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
<title>My 1st test</title></head>
<html>
<body>
<div id="pagina">
<h1>System XPTO</h1>
<div>
Data: <span id="DATA">ND</span><br>
Hora: <span id="HORA">ND</span><br>
Temperatura Ambiente: <span id="TEMPAMB1">ND</span>
</div>
<div id="botoes">
<button type="button" onclick="sendData(0)" style="width: 80px; height: 30px; margin: 30px;">ON</button>
<button type="button" onclick="sendData(1)" style="width: 80px; height: 30px; margin: 30px;">OFF</button><BR>
</div>
<script>
setInterval(function() {
// Call a function repetatively with 1 Second interval
getData();
}, 1000); //2000mSeconds update rate
//function to set on / off a LED on my board
function sendData(led) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LEDState").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "setLED?LEDstate="+led, true);
xhttp.send();
}
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
</script>
</div>
</body>
</html>
)=====";
My problem is...I don't know how to modify this script to get more sensors values from the described above function.
Anybody can save me please?
Thanks in advance ;)
The standard XMLHttpRequest only supports responseText and responseXML, it does not support responseJSON property. However, as long as your server is sending a valid serialised JSON string, the responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse(), and then you can access each JSON element with dot notation:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
This piece of code works for all browsers that supports XMLHttpRequest and JSON as long as the server is sending a valid JSON object.
Can someone help me parse the value of an element from nested JSON response. I want to display value or "priceInCents" on HTML page here is my script
<!DOCTYPE html>
<html>
<body>
<div id="demo1">
<h1>Product price</h1>
<button type="button" onclick="loadDoc1()">check price</button>
</div>
<script>
function loadDoc1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("demo1").innerHTML = obj.results.price.priceInCents;
}
};
xhttp.open("GET", "http://search.mobile.walmart.com/search?query=329264833&store=148", true);
xhttp.send();
}
</script>
</body>
</html>
results is an array, so you have to specify that you want the first element of the array.
function loadDoc1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("demo1").innerHTML = obj.results[0].price.priceInCents;
}
};
xhttp.open("GET", "https://search.mobile.walmart.com/search?query=329264833&store=148", true);
xhttp.send();
}
<div id="demo1">
<h1>Product price</h1>
<button type="button" onclick="loadDoc1()">check price</button>
</div>
How can I load a spinning icon when using xmlhttprequest in JavaScript while Ajax is processing and I want to direct it to an innerHTML of a tag
Instead of 'Loading...' just use your spinner image and correct the path to your_file.txt to get a response from server:
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
setTimeout(function(){
document.getElementById("demo").innerHTML = res;
}, 2000);
} else {
document.getElementById("demo").innerHTML = 'Loading...';
}
};
xhttp.open("GET", "your_file.txt", true);
xhttp.send();
}
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
You don't need the setTimeout either - it's just for demo purposes, so you can actually see and verify the spinner when the response comes back way to fast, i.e. on localhost.