0

I want to do something that seems simple enough, yet I am struggling quite a lot (I am new to Javascript).

I want to get the value from this page https://blockchain.info/q/24hrprice (bitcoin api for today's price). I want to put this in a javascript variable and then display it on my web page.

Here's what I got so far:

<input type="text" id="mytext">

<script>
var test = $.getJSON("https://blockchain.info/q/24hrprice");
var todayvalue = test.done(function(response) { console.log(response); });
document.getElementById("mytext").value = todayvalue;
</script>

If I check my console, the value is found and there is no error message but all I get on my web page is a box with [object Object] and nothing in it.

Do you guys know what I am doing wrong?

Thanks a bunch

user1983400
  • 369
  • 3
  • 4
  • 10
  • 1
    write the line `document.getElementById("mytext").value = response;` inside the callback function – Sunand Sep 22 '14 at 22:11
  • You are forgetting that your ajax call is asynchronous. See related answer here: http://stackoverflow.com/a/14220323/361762 – Dave Sep 22 '14 at 22:15
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Dave Sep 22 '14 at 22:15
  • It works! Thanks a lot! Although I dont really get the concept of the callback function yet, I will definitely look into from now on...it looks really important! – user1983400 Sep 22 '14 at 22:15

2 Answers2

1

You'll want to put the document.getElementById("mytext").value = response; in your success callback.

var promise = $.getJSON("https://blockchain.info/q/24hrprice");

promise.done(function(todayValue) {
    console.log(todayValue);
    document.getElementById("mytext").value = todayValue;
});
caseyWebb
  • 1,997
  • 17
  • 18
0

$.getJSON() (and $.getJSON.load()) returns a jqXHR object, which is what you get in your varaible todayvalue.

Accessing the response is done in the callback from $.getJSON()

And since you already loaded jQuery, stick to that. Here's and example of what you probably want to do:

$.getJSON("https://blockchain.info/q/24hrprice", function(response){
        $("#mytext").val(response);
    });
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28