let xhr = new XMLHttpRequest();
xhr.open("GET", "https://reqbin.com/echo/get/json");
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
};
xhr.send();
let a = xhr.responseText
Why can't I save the value of variable 'a' right away?
I can not get the value {"success":"true"}
how can i get?
Since this request is happening asynchronously your
let a = xhr.responseText
code is executing before the server returns a response
In that case what you can do is place the code that you want to execute inside onreadystatechange event handler, which will execute after server has returned you a response.
let xhr = new XMLHttpRequest();
let a;
xhr.open("GET", "https://reqbin.com/echo/get/json");
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
a = xhr.responseText
}
};
xhr.send();
Related
How can I check if the response received from XMLHTTPRequest has a particular class or not?
async function swipeAction(currentElementObj) {
var cardId = currentElementObj.getAttribute("value");
var dataString = {'card': cardId};
let response = await new Promise(resolve => {
var xhr = new XMLHttpRequest();
xhr.open("POST", "processes/explore.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(dataString));
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// I WANT TO CHECK SOMETHING LIKE THIS
if(xhr.response.getElementById("matched").classList.contains('matched'))
alert(xhr.response.getElementById("matched").classList);
}
}
});
}
In the response received, I want to check if the element with id matched has a class name matched or not. However, the above code isn't working. What should be the proper approach here?
If you're expecting plain text/html response from the server then processing it may look like that:
async function swipeAction(currentElementObj) {
var cardId = currentElementObj.getAttribute("value");
var dataString = { card: cardId };
let response = await new Promise((resolve, reject) => {
try {
var xhr = new XMLHttpRequest();
xhr.open("POST", "processes/explore.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
// add responseType = "document" for response to be parsed into DOM
xhr.responseType = "document";
// override response mime type (in case your server sends text/plain)
xhr.overrideMimeType("text/html");
xhr.send(JSON.stringify(dataString));
xhr.onreadystatechange = function () {
// check for non-empty responseXML property
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseXML) {
const matched = xhr.responseXML.getElementById("matched");
if (!matched) return reject("Element not found in response");
if (matched) {
alert(matched.classList.contains("matched"));
resolve(true);
}
} else {
return reject("Incompatible response format");
}
};
} catch (e) {
reject(e.toString());
}
});
}
I have an http request which delivers 'JSON.stringify(data)'.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/api/hello", true);
xhr.send();
xhr.onreadystatechange = function () {
console.log(xhr.responseText);
};
How can I run the code and print the contents of data?
your code should be working, the endpoint may be the problem, check the url your trying to get into the endpoint from, then don't forget to check the readyState and the status of your request before doing nothing.
xhr.onreadystatechange = function () {
if (xhr.readState === 4 && xhr.status === 200)
{
console.log(xhr.responseText);
}
};
Hi, I am trying to extract something from an API, which should return me a string with the recent prices for Ethereum.
After that I would like to parse the string and drop all data, so that only the latest price is returned.
This is the code I have so far, however it does not return anything and I am stuck on this and how to parse the code.
Any help is greatly appreciated! Thanks.
{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
}
};
You're not sending the request. You need to add xhr.send(); to send the request. Here is the sample request.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(this.responseText);
}
};
xhr.send();
After creating your xhr and adding the proper callbacks to it, make sure to invoke xhr.send(). The response from that endpoint seems to be a JSON object, so you can invoke JSON.parse() on the response to turn it into a javascript object that you can work with.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Parse JSON response
var data = JSON.parse(xhr.responseText);
// Use the object however you wish
console.log(data);
}
}
xhr.send();
You must call the xhr.send(); function to actually send the request. Otherwise you have just initialized the request and also set up the callback function to handle the response but no request to the API is sent.
I'm trying to get the result, next time of the game in database. I used XMLHttpRequest with 5s delay of setInterval to fetch data. If the status of the request is 200. The code works well. However, if the status is not 200. The clearInterval will not work but console.log still works.
var _resInterval;
_resInterval = setInterval(function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/index.php/forms/getDDResult/" + id, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
var _resp = JSON.parse(xhr.responseText);
console.log(_resp);
if (parseInt(_resp.interval) >= 0) {
clearInterval(_resInterval);
restartGame(parseInt(_resp.interval));
}
} else {
console.log("error");
clearInterval(_resInterval);
}
};
xhr.send();
}, 5000);
UPDATE: recursive function
function getGameResult() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/index.php/forms/getDDResult/" + id, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
var _resp = JSON.parse(xhr.responseText);
console.log(_resp);
if (parseInt(_resp.interval) >= 0 && _resp.result != "Not available") {
restartGame(parseInt(_resp.interval));
} else {
setTimeout(function() {
getGameResult();
}, 5000);
}
}
};
xhr.send();
}
Am I doing it the right way or should I change it to recursive function? Thanks.
-- Lara
The problem is that there's a possibility where the clearInterval is called and an XHR is pending a response. When the browser receives the response, the timer is long gone, but still has to handle the response.
If you want your periodic XHR to wait for the response of the previous before launching another, the recursive setTimeout is a better option.
I have the following code for my request:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) // state of 4 is 'done'. The request has completed
{
callback(req.responseText); // The .responseText property of the request object
} else { // contains the Text returned from the request.
console.log(req.readyState);
}
};
req.open("GET", url, true);
req.send();
However, the readyState is changing to 1 and firing correctly (I'm seeing it echoed in the console) but it simply won't progress to 2. After awhile it times out and I get this in the console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Uncaught SyntaxError: Unexpected end of input
Anyone have any idea why this might be?
Put this
req.open("GET", url, true);
req.send();
above this line
req.onreadystatechange = function() {
Sorry all, this ended up being a VPN issue, not a scripting one.
function getLatestfileinAllPath(urls)?
{
for(i = 0;i<urls.length;i++){
run(i)
}
function run(){
var request = new XMLHttpRequest();
request.open('POST', url[i]);
request.send(JSON.stringify({"data":"some data"}));
request.onreadystatechange = function()
{
if (request.readyState === XMLHttpRequest.DONE && request.status == 200)
{
console.log(JSON.parse(request.response));
}
}
};
}
}