Reputation: 175
Hello I am trying to create a simple javascript that pulls data from a REST API. I am looking to only pull 1 data set within the API or json list of items.
Where as I only need the "last" data set to be included within the population not everything else.
I have tried using a different method of retriving the last price data set via curl however the resource blocks requests in php. Thus I need to do this with javascript.
document.getElementById("output").innerHTML = (ourRequest.responseText);
I have tried changing this section to be
document.getElementById("output").innerHTML = (ourRequest.responseText.last);
and a few other variables however returned no success on the output.
Below is the js code that I have made so far however it shows all the API information on the page where I only need to select 1 part of the information.
<p id="output"></p>
<script>
var burl = "https://api.idex.market/returnTicker?market=ETH_STASH";
var url = burl;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
document.getElementById("output").innerHTML = (ourRequest.responseText);
}
ourRequest.send();
</script>
I am expecting to have only 0.00000001512001 as the result being the "last" data set.
and the output is the following:
{"last":"0.00000001512001","high":"0.00000015","low":"0.00000001512001","lowestAsk":"0.00000058999999999","highestBid":"0.00000001","percentChange":"-89.91999333","baseVolume":"0.965950839330223243","quoteVolume":"24272447.879302712135495139"}
You can test and edit it here to try: https://www.w3schools.com/code/tryit.asp?filename=FYUDV3ZFYNA9
Upvotes: 0
Views: 2507
Reputation: 1792
Try changing
document.getElementById("output").innerHTML = (ourRequest.responseText);
to
document.getElementById("output").innerHTML = (JSON.parse(ourRequest.responseText).last);
Full working solution:
<script>
var burl = "https://api.idex.market/returnTicker?market=ETH_STASH";
var url = burl;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
document.getElementById("output").innerHTML = JSON.parse(ourRequest.responseText).last;
}
ourRequest.send();
</script>
Upvotes: 1
Reputation: 182
Convert the responseText to a valid JavaScript Object using
let returned_data = JSON.parse(ourRequest.responseText);
Then access the last property as
last = returned_data['last'];
<script>
var burl = "https://api.idex.market/returnTicker?market=ETH_STASH";
var url = burl;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
let returned_data = JSON.parse(ourRequest.responseText);
let last = returned_data['last'];
document.getElementById("output").innerHTML = last;
}
ourRequest.send();
</script>
Upvotes: 0