Getting data from an API and parsing it with javascript - 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.

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

Execute a http request response in 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);
}
};

XMLHttpRequest - I have problem when REST API returns JSON object and not array of object

I have simple REST API which returns one JSON object under endpoint .../statistics
I am trying to get this object in js script but response text from XMLHttpRequest is empty.
I noticed that response text is not empty when API returns arrays of JSONs.
This is my js function in script:
function httpGet(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false); // false for synchronous
xmlHttp.send();
return xmlHttp.responseText;
}
So when API response is only one JSON object xmlHttp.responseText is empty.
When API response is arrays of JSONS it works fine.
var url = 'somePage.html'; //A local page
function load(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.response);
}
}
xhr.open('GET', url, true);
xhr.send('');
}

How to use the result from a API call for another call?

I hope someone can help me, because i can't get it to work and it's really frustrating.
I have the following code
var getJSON = (url, callback) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.response);
}
};
xhr.send();
};
I want to use it to get a json object from the given url but inside the function I want to use the response to get another json object back.
var func1 = (url) => {
getJSON(url, (data) => {
//Do smth here with the data and then for example
func2('https://someurl.com/api/somefunction/' + data.smth.age);
});
}
Now the problem is that in func2 the data will be null or undefinded and it doesn't work after that.
In addition I have more than 2 functions which try to call getJSON.
I hope someone has a solution.

XMLHttpRequest returns wrongly encoded characters

I use XMLHttpRequest to read the PDF document
http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf
%PDF-1.3
%âãÏÓ
[...]
and print its content out to console:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
console.log('âãÏÓ');
}
};
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.send();
However, the console says
%PDF-1.3
%����
[...]
âãÏÓ
(The last line is from the reference console.log above to verify that the console can actually display those characters.)
Apparently, the characters are wrongly encoded at some point. What's going wrong and how to fix this?
XMLHttpRequest's default response type is text, but here one is actually dealing with binary data. Eric Bidelman describes how to work with it.
The solution to the problem is to read the data as a Blob, then to extract the data from the blob and plug it into hash.update(..., 'binary'):
var xhr = new XMLHttpRequest();
xhr.open('GET', details.url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status === 200) {
var a = new FileReader();
a.readAsBinaryString(this.response);
a.onloadend = function() {
var hash = crypto.createHash('sha1');
hash.update(a.result, 'binary');
console.log(hash.digest('hex'));
};
}
};
xhr.send(null);
The MIME type of your file might not be UTF-8. Try overriding it as suggested here and depicted below:
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.overrideMimeType('text/xml; charset=iso-8859-1');
xhr.send();

Categories