How to obtain the body response in the client-side? - javascript

I am new in web, I am serving an html when a button is clicked on the client side through a request, the body response of that request is the html. How can I retrieve the html or body response from the client side?
I am trying with this code but everything is empty:
var xhr = new XMLHttpRequest();
xhr.open(signedRequest.method, signedRequest.url, true);
console.log('xhr.response: ', xhr.response);
console.log('xhr.responseText: ', xhr.responseText);
console.log('xhr.responseXML: ', xhr.responseXML);
document.write('<p>xhr: ' + xhr + '</p>');
xhr.send();
Any idea on how to obtain the body response in the client-side?

Try to add a div or any input element with the id "demo" and try to run the code below.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "<strong>The response from the test URL is: </strong>" + this.responseText;
console.log(JSON.parse(this.response));
}
};
xhttp.open("GET", "https://httpbin.org/get", true);
xhttp.send();
<div id="demo"></div>

Related

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.

Asmx webservice Xmlhttprequest content-type

I have a piece of javascript code for accessing a asmx webservice
var xml = 'xml=<Webservice><Parameters><Parameter name="PARTCODE" value="WSA10029" /></Parameters></Webservice>';
try {
xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.send(xml);
} catch (e) {
alert('Error occured in XMLHttpRequest: ' + xhr.statusText + ' ReadyState: ' + xhr.readyState + ' Status:' + xhr.status);
}
The webservice receives the request but the parameter xml is empty at the webservice side. i've tried many different Content-Types but none of them work.
Data data I want to send is xml, therefor I htmlencoded the xml.

Cannot get proper response in xhttp in javascript?

I am using following AJAX code
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 ) {
alert("Status : " + this.status);
alert("Response : " + this.responseText);
}
};
xhttp.open("GET",url,true);
xhttp.send(null);
}
The problem is that I am unable to get the response. The responseText has no value and status is 0.
I checked in fiddler, the request is properly completed. Fiddler shows the correct response. I checked it by debugging on console, the xhttp doesnot update after xhttp.send().
This code is running inside an IFrame.

send content to other page using script

I have written a code in script which is given below.
function myFunction(a) {
var k=a;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ques").innerHTML = this.responseText;
}
};
xhttp.open("GET", "retrieveQuestion.php?question=" +a, true);
xhttp.send();
var q="<td><input type='text' name='answer' id='ans' placeholder='submit your answer here'/></td>" ;
document.getElementById("t2").innerHTML=q;
var answ = document.getElementById("ans").value;
var z="<td align='center'><input type='button' value='submit' onclick='myfunc1(k,answ)'/></td>";
document.getElementById("t3").innerHTML=z;
}
function myfunc1(q1,a1)
{
xhttp.open("GET", "checkanswer.php?question=" +q1 + "&a1=" +a1, true);
xhttp.send();
}
Now when i click on submit button it did not redirected to checkanswer.php
can anyone help me in this problem.
Using xhttp.open is sending a background request to checkanswer.php, rather than actually redirecting to it. You'd need to use something like window.location instead.

Display response(xml) by making a HTTP GET request using javascript?

I have very new to JS and I have done my research but I guess I'm kind of using the wrong technique or something.
Like in python to make GET request we do:
request_text = requests.get(url).text
I want to do the same thing but using JS i.e. display the content from "http://synd.cricbuzz.com/j2me/1.0/livematches.xml" in the raw(xml) format and I have found this script somewhere but it doesn't work.
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "http://synd.cricbuzz.com/j2me/1.0/livematches.xml", false);
xhttp.send();
}
</script>
</body>
</html>
I just need the direction on how to do the same i.e. how to send a GET/POST request using JS and render it on a webpage?
When I use
function test(url) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
var section = document.createElement('section');
var h2 = document.createElement('h2');
h2.textContent = 'Received from ' + url;
section.appendChild(h2);
var pre = document.createElement('pre');
pre.textContent = req.responseText;
section.appendChild(pre);
document.body.appendChild(section);
};
req.onerror = function(evt) {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '.<\/p>');
};
req.send();
}
document.addEventListener('DOMContentLoaded', function() {
test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml');
test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml');
},
false);
the first URL works as the server is set up to allow the CORS request for that directory while the second fails as the server does not allow it. So unless you serve your HTML with the script from synd.cricbuzz.com or unless you can change the configuration of synd.cricbuzz.com to allow a CORS request you won't be able to request the XML from that server.
Note also that in modern browsers (current versions of Mozilla, Chrome, Edge) you can use the Promise based fetch method instead of XMLHttpRequest, as shown below. But the same origin policy is not different for fetch, so the same as stated above holds.
function test(url) {
fetch(url).then(function(response) {
if(response.ok) {
response.text().then(function(text) {
var section = document.createElement('section');
var h2 = document.createElement('h2');
h2.textContent = 'Received from ' + url;
section.appendChild(h2);
var pre = document.createElement('pre');
pre.textContent = text;
section.appendChild(pre);
document.body.appendChild(section);
});
}
else {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '; status: ' + response.status + '.<\/p>');
}
})
.catch(function(error) {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error "' + error.message + '" requesting ' + url + '.<\/p>');
});
}
document.addEventListener('DOMContentLoaded', function() {
test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml');
test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml');
},
false);

Categories