0

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

2
  • 2
    add xhr.send() to send the request Commented Dec 12, 2017 at 6:02
  • Let's say you created an associative Array response on the Sever with PHP, which you should do, in my opinion. Then you echo json_encode($assoc_array_here); on your PHP page. Of course, using the raw XMLHttpRequest with XMLHttpRequestInstance.responseText will give you that associative Array as a String. Use JSON.parse(XMLHttpRequestInstance.responseText) or eval('('+XMLHttpRequestInstance.responseText+')'). The later is more backward compatible. JSON.parse() is what most will recommend. Commented Dec 12, 2017 at 6:14

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.