Javascript i can't add a new paragraph using ajax - javascript

Hi im having this problem, when i use the code only for the (without the "demo2" ) works fine, and in the browser i can see the text that its on "PruebasGeneral/MBVR000008.txt" and when i change this file/text, works in my HTML without refreshing, but i need to add another as you can see, i tried to add in the same function, but doesnt work, with this code in the browser in the two paragraph shows whats inside "PruebasGeneral/MBVR000009.txt" so basically shows demo2 and demo2. WHAT SHOULD I DO?
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function loadDoc(path, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.responseText);
}
};
xhttp.open("GET", path + "?t=" + Math.random(), true);
xhttp.send();
}
function data1Loaded(data) {
document.getElementById("demo").innerHTML = data ; // do something with data
}
function data2Loaded(data) {
document.getElementById("demo2").innerHTML = data ; // do something with data
}
function loadDocs() {
loadDoc('/PruebasGeneral/MBVR000008.txt', data1Loaded);
loadDoc('/PruebasGeneral/MBVR000009.txt', data2Loaded);
setTimeout(loadDocs, 1000);
}
window.onload = loadDocs;
</script>
</body>
</html>

You need to have all of that over again. You can't just call open() twice:
function loadDoc(path, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.responseText);
}
};
xhttp.open("GET", path + "?t=" + Math.random(), true);
xhttp.send();
}
function data1Loaded(data) {
// do something with data
}
function data2Loaded(data) {
// do something with data
}
function loadDocs() {
loadDoc('path1', data1Loaded);
loadDoc('path2', data2Loaded);
setTimeout(loadDocs, 1000);
}
window.onload = loadDocs;

Related

Parsing JSON Array to print specific elements

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

inject jsp with js result into html>body>div

My question is: Could insert a jsp response (html) in html?
I think using XmlHttpRequest.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.jsp", true);
xhttp.send();
My question is: But if I have javascript in my jsp that it executes after page loading, is it executed like when I call jsp directly by browser url?
Thanks in advance
For example:
This is index.html
<html>
<head>
<script type="text/javascript" src="app.js"></script>
</head>
<body onload="loadInfo();">
<div id="container"></div>
</body>
This is app.js:
function loadInfo(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("container").innerHTML =this.responseText;
}
};
xhttp.open("GET", "info.html", true);
xhttp.send();
}
This is info.html (i have jsp but i think it is the same..):
<html>
<head>
<script type="text/javascript" src="info.js"></script>
</head>
<body>
<div id="body_info">This is info..</div>
<script type="text/javascript" >
console.log("wait for info..");
info();
</script>
</body>
This is info.js:
function info(){
document.getElementById("body_info").innerHTML ="info.js is executed";
}
If i call info.html, typing url in browser(example http://localhost:8000/info.html), the script is executed and i get
"info.js is executed",instead if i call index.html, maybe the xhr request not return the same but I see "This is info".
how can i resolve and accomplish this problem using xhr?
Thanks
Roberto
When you make ajax called to some page so what ever will there under <body></body> will return as response so in your code this.responseText will be having <script></script> code in it also. You can check if you are using chrome then click on element tab you will see <script></script> also which is return as response .Now,to execute this you can do like below :
function loadInfo() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("container").innerHTML = this.responseText;
//getting the script which is return as response back
var datas = document.getElementById("container").getElementsByTagName("script");
//looping unders <script></script>
for (var i = 0; i < datas.length; i++) {
console.log("inside script executing")
eval(datas[i].innerText); //executing script
}
}
};
xhttp.open("GET", "n.html", true);
xhttp.send();
}
And your script for info.html look like below :
<script>
console.log("wait for info..");
info();
function info() {
document.getElementById("body_info").innerHTML = "info.js is executed";
}
</script>

How to parse json using ajax script in ESP32 app

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.

jQuery not working with XMLHttpRequest object

I have an index.php page which loads info.php through AJAX. The info.php content is loaded like this:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhttp.open("GET", "info.php", true);
xhttp.send();
}
(function() {
loadDoc()
})();
setInterval ( "loadDoc()", 5000 );
</script>
The info.php file has the following code to do a count up/down from/to a specific number.
<div class="timer count-title count-number" data-from="2000" data-to="300" data-speed="1500"></div>
<script src='includes/jquery-3.2.1.min.js'></script>
<script src="includes/counter.js"></script>
When I visit info.php directly the counter works perfectly fine. However, if I visit index.php, the counter is not even showing. I had the same issue with other jQuery scripts. Even if index.php includes jQuery and the other scripts it still doesn't work. I do want the number to go through the AJAX call since it keeps updating.
Is there a simple solution?
you can do it by JQuery like as follow...
function loadDoc(){
console.log( "call done" );
$( "#data" ).load( "info.php", function() {
console.log( "Load done." );
});
};
$(function(){loadDoc();});
setInterval (loadDoc, 5000 );
I think their problem with your function statement checks this for the following script...
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhttp.open("GET", "info.php", true);
xhttp.send();
}
$(function(){loadDoc();});
setInterval (loadDoc, 5000 );

getElementsByTagName Stopped Working

I'm trying to populate an HMTL page with XML data. This code used to work but I must have changed something because now nothing happens on the button clicks. Could it potentially be a problem with the server? And in that case what changed? The line where things appear to stop working is getElementsByTagName, all alerts before that line still work.
Here's the scripts:
<script type="text/javascript">
function loadXMLDocTraditional() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//alert("Xhttp.readyState = " + xhttp.readyState);
var xmlDoc = xhttp.responseXML;
//There is something wrong with this line
var item = xmlDoc.getElementsByTagName("trad")[0].childNodes[0];
document.getElementById("data").innerHTML = item.nodeValue;
}
};
xhttp.open("GET", "data.xml", true);
xhttp.send();
}
function loadXMLDocSimple() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
//alert("Xhttp.status = " + xhttp.status);
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlDoc = xhttp.responseXML; //Using a variable doesn't work bc/ of the getElements method?
var item = xmlDoc.getElementsByTagName("simp")[0].childNodes[0];
document.getElementById("data").innerHTML = item.nodeValue;
}
};
xhttp.open("GET", "data.xml", true);
xhttp.send();
}
</script>
And here's the XML:
<dictionary>
<word>
<title>Ubiquitous</title>
<trad>This is the traditional defintion ubiquitous</trad>
<simp>This is the simplified defintion hopefully ubiquitous</simp>
</word>
<word>
<title>Lithe</title>
<trad>This is the traditional defintion of lithe</trad>
<simp>This is the simplified defintion of lithe hopefully</simp>
</word>

Categories