Reputation:
I'm doing a currency converter and what I intend to do is when the page is loaded it use document.ready function to call a ajax to show a standard currency. But it doesn't.
There's a keypress function to do the same and it works. So, the problem is that it doesn't show when load the page but only on keypress function.
Some one can give a hand?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="layout.css">
<script src='jquery.js'></script>
<title>Calculator Teste</title>
</head>
<body>
<header>
<div id="logo">Money Converter</div>
</header>
<div id="wrapper">
<div id="from_select">
<select name="from" id="from">
<option selected="selected" value="USD">United States Dollars - USD</option>
<option value="EUR">Euro - EUR</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="INR">India Rupees - INR</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="CHF">Switzerland Francs - CHF</option>
...
</select>
</div>
<div id="to_select">
<select name="to" id="to">
<option selected="selected" value="EUR">Euro - EUR</option>
<option value="USD">United States Dollars - USD</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="JPY">Japan Yen - JPY</option>
...
</select>
</div>
<div id="result"><i>getting info...</i></div>
<input type="number" class="amount" name="amount" id="amount" value="1.00" autofocus/>
</div>
</body>
<script>
var rate = null;
getRate = function() {
// Getting Values
var from = $('#from').val();
var to = $('#to').val();
url = "http://rate-exchange.appspot.com/currency?from=" + from + "&to=" + to + "&calback=jsonpCallback";
$.ajax({
url: url,
type: "POST",
async: false,
dataType: "jsonp",
success : function(data)
{
rate = parseFloat(data.rate);
}
});
};
getRate();
showConvertion = function(){
var amount = $('#amount').val();
result = amount * rate;
// alert(result);
$('#result').html(result.toFixed(2));
};
$(document).ready(function (){
getRate();
showConvertion();
});
$('#from').change(function (){
getRate().then(showConvertion);
});
$('#to').change(function (){
getRate().then(showConvertion);
});
$('#amount').keypress(function (){
showConvertion();
});
</script>
</html>
Upvotes: 0
Views: 2741
Reputation: 6946
The problem is that you're mixin asynch with synch :
$(document).ready(function ()
{
getRate();
showConvertion();
});
When ShowConvertion
is called, the AJAX call you make in getRate hasn't probably returned yet, so your rate
variable you use in ShowConvertion
is probably not set at the time. You should wrap the ShowConvertion
call into the success function of your ajax call :
success : function(data)
{
rate = parseFloat(data.rate);
showConvertion();
}
Upvotes: 1