1

I'm trying to take a value that a php page outputs and use it later as a variable in a calculation. Currently I am trying this:

var price = function() {
      $.get('gox.php')
  }


function toDol(elem) {
    var btcToDol = parseFloat(elem.value) * price || '';
    document.getElementById('dol').value = btcToDol.toFixed(2);
}

function toBtc(elem) {
    var dolToBtc = parseFloat(elem.value) / price || '';
    document.getElementById('btc').value = dolToBtc.toFixed(4);
}

The important part is I want the 'price' variable to equal the value gox.php outputs (e.g. 99.9999) so that I can use it later to do the math in functions 'toDol' and 'toBtc'.

Thank you for your help!

1
  • Are you sure the HTTP overhead is worth the number of calls to get an up-to-date BTC to USD currency rate? Why not just use a random number generator? Commented Jul 18, 2013 at 1:02

2 Answers 2

4
var price = 0;
$.get('gox.php').done(function(data) {
  price = data;
});
Sign up to request clarification or add additional context in comments.

3 Comments

Make sure you convert data to a number so that the math operation will work. parseInt(data, 10) or Number(data)
@Shawn31313 You don't need to convert it to a number. The / and * operators automatically (attempt to) convert its operands.
@Shawn31313 It's not a bad thing to do though, because it explicitly shows what's happening. I'd stick with Number (or + - the unary plus operator, which acts the same), because parseFloat and parseInt allows invalid characters at the end of a string and still parses. And of course, the + does tricky things based on the operands (like using/mixing strings in with numbers)
0

Try the following code

var price=$.ajax({
    type: 'GET',
    url: 'gox.php',
    global: false,
    async:false,
    success: function (data) {return data;}
}).responseText;

I always have issues with $.get and $.post

1 Comment

This a lot more complicated than @elzars answer.

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.