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

4
  • 1
    write the line document.getElementById("mytext").value = response; inside the callback function Commented Sep 22, 2014 at 22:11
  • You are forgetting that your ajax call is asynchronous. See related answer here: stackoverflow.com/a/14220323/361762 Commented Sep 22, 2014 at 22:15
  • possible duplicate of How to return the response from an Ajax call? Commented Sep 22, 2014 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! Commented Sep 22, 2014 at 22:15

2 Answers 2

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

Comments

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

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.