Trrrrrrrrrr Trrrrrrrrrr - 3 years ago 163
HTTP Question

How do I make an HTTP request to bitstamp?

I'm trying to use an API from bitstamp to fetch a currency trading price on my webpage.

I have researched this problem, but I still cannot get it to work as it always returns

ERROR


The link used is
https://www.bitstamp.net/api/ticker/
and the response should be
last


Here is my code:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
}
else {
window.alert("ERROR");
} }

Answer Source

Try this:

function loadXMLDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    var jsonRes= JSON.parse(this.responseText);
    		if (jsonRes.hasOwnProperty('last')) {
                 alert(jsonRes.last);
    
}
    }
  };
  xhttp.open("GET", "https://www.bitstamp.net/api/ticker", true);
  xhttp.send();
}
<h2>Using the XMLHttpRequest object</h2>

<button type="button" onclick="loadXMLDoc()">Change Content</button>

<p id="demo"></p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download