Execute a http request response in javascript - javascript

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);
}
};

Related

Check if POST was successful and then run JavaScript

How do I check, if a POST XHR request was successful, on a website, for a particular URL?
If the POST was successful, I then want to run some JavaScript.
I've seen ways to do this in jQuery, but I want to do this via vanilla JavaScript.
You can use the status code to check if the request was successful:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// successful
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send();
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status
https://stackoverflow.com/a/3038972/10551293

Getting data from an API and parsing it with javascript

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.

clearInterval not working with XMLHttpRequest

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.

xmlHttpRequest status = 0

I have a website (wagtail CMS) running at AWS at domain:8000 and my API running at domain:8801
On my webpage I try to get some info from API by using JS (Access-Control-Allow-Origin header is set correctly at API, it's a django-based app)
Unfortunately the following code returns only xhr.status = 0 and empty responseText no matter what I try to access.
When I put domain:8000 at xhr.open('GET','http://domain:8000',true) everything works just fine, I see my html code.
function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
}
else {
alert( "SUCCESS" );
}
}
On the API side I see all my requests, status=200 in server console.
You're supposed to use a callback function to catch the response from a request using the XMLHttpRequest object. Do something like this instead:
xhr.addEventListener('readystatechange', function() {
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
} else {
alert( "SUCCESS" );
}
}
});
Look here for docs and an examples on doing that.
You need to wait for xhr.readyState == 4 before xhr.status is at all valid (actually I think it's valid at 3, but lets keep consistent with 99.999% of code in the wild)
function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
}
else {
alert( "SUCCESS" );
}
}
};
xhr.send();
}

onreadystatechange only firing once

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));
}
}
};
}
}

Categories