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