0

I have a program that calculates bitcoin mining profitability and thus requires the live price of bitcoin, but I also want the user to be able to edit the price after it is initially loaded as the live price.

The problem I'm running into is that when I run my code bpv goes initially as undefined, even though it should be called when the body loads, theres no issue with the ajax call because once run update after the body has loaded, bpv gets defined.

I suspect this is because the ajax call takes longer than the page takes to load, leaving bpv undefined, then when I run update() the code is already initialized so theres no delay.

What I also suspect would fix this would be to make the page wait to load until the ajax call has been sent back, but I can't imagine this being scaleable at all?

I'm very new to this so try and be easy on me, thanks.

<head>
var bpv;
function update(){
getVal();
getPrice();
function getPrice(){
    $.ajax({
        dataType:"json",
        type: 'GET',
        url:'https://blockchain.info/ticker',
            success: function(data){
                 bpv = data.USD.last;       
            }

    });
}

}

</head>
<body onload = "update()" >
<script>
function getVal(){
//Current Value of Bitcoin
        bpv = document.getElementById("bp").value;
</script>
Value of Bitcoin ($)<br/>
        <input type="text" id="bp" onKeyDown="getVal()" onKeyUp="getVal()" value="" ><br/>  

EDIT: I used Alex's solution, although it only fixed the input displaying undefined, and not the end result of the calculations, so if implemented a very janky solution in where I run the calculation again, .1 seconds after the page has loaded, if anyone whos smarter than me knows a better solution my ears are wide open

  • 1
    You should use promises. – SLaks Oct 09 '17 at 21:47
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Oct 10 '17 at 14:21

3 Answers3

0

So a couple things.

  • Your first tag is this is not valid. The head tag needs to contain proper contents. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head
  • Move all the javascript inside of the script tag
  • function getVal(){ is not properly formatted and has invalid syntax. you are missing a closing bracket
  • Instead of trying to set bpv after you make the AJAX call, update the value of the DOM document.getElementById("bp").value = data.USD.last
d3l33t
  • 890
  • 6
  • 10
  • I should've specified that I just cut out these relevant portions of code, but when I load my page it doesn't encounter any errors – Donkeypunter Oct 10 '17 at 12:50
0

Ajax calls are asynchronous. So the rest of the page will always execute while the call is being done. I'm not exactly sure what you are trying to accomplish, but if you wish to show the value of Bitcoin on the input box and then let users change it after it's been loaded, you could follow something like:

  • Start with input box disabled;
  • Load bitcoin with AJAX call;
  • Set the response price into the field;
  • Enable the field so users can edit;

That could look like: (I'm removing part of the code to exemplify, but if you have any questions let me know)

  <head>
  <script>
  var bpv;
  document.addEventListener("DOMContentLoaded", function(event) {
    getPrice();
  });

  function getPrice(){
    $.ajax({
      dataType:"json",
      type: 'GET',
      url:'https://blockchain.info/ticker',
      success: function(data){
        bpv = data.USD.last;
        setPriceInput(bpv);    
      }
    });
  }

  function setPriceInput(value) {
    var input = document.getElementById('bp');
    input.value = value;
    input.disabled = false;
  }
  </script>
  </head>
  <body>
    Value of Bitcoin ($)<br/>
    <input type="text" id="bp" value="" disabled>
  </body>

https://jsfiddle.net/81oqsk5x/1/

This solution will wait for the page to be rendered, then try to get the price. Once the price is responded from the API, it will set the price on the input and enable it again (if you look at the input element, it starts as disabled)

Alex Santos
  • 2,900
  • 1
  • 19
  • 21
  • I've implemented that code, thanks, but I run also run a calculation with that bpv, and while the input box holds the correct value, the calculations see bpv as undefined, not sure how I'd go about fixing this? – Donkeypunter Oct 10 '17 at 14:01
  • @Donkeypunter that is a more specific issue. If you can paste your code on jsfiddle, I can take at your problem and try to suggest a solution – Alex Santos Oct 10 '17 at 14:39
-1

Always put your Jquery code within the Ready function

$(document).ready(function(){
   // your code here
});
Victor Hugo Terceros
  • 2,969
  • 3
  • 18
  • 31