1

First of all, I'm using JQuery. Take a look:

$(document).ready(function() {
    var btcusd = 600;

    function getRate() {
        $.get("rate.php", function(data) {
            var btcArr = JSON.parse(data, true);
            btcusd = btcArr["last"];
            //This will give me the correct value
            console.log(btcusd);
        });
    }

    setInterval(function() {

        //This will say 600 every time
        console.log(btcusd);

        //Update rate for next loop
        getRate();

    }, 3000);
});

Chrome console gives me the 600 every 3 seconds. If I do this manually in the chrome live console, I will get a real value, like 595.32.

Why does this not work like intended? Thanks for help.

Standard
  • 1,450
  • 17
  • 35
  • 1
    php code? as you set btcusd from the response it is more likely, that your php code is broken – Tobbe Jun 19 '14 at 23:18
  • See http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Barmar Jun 19 '14 at 23:20
  • Also see http://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function-asynchron?newsletter=1&nlcode=97716%7c4ba7 – Barmar Jun 19 '14 at 23:20
  • @Tobbe if I output btcusd inside getRate(), everything is fine – Standard Jun 19 '14 at 23:27

1 Answers1

0

I think @Tobbe is quite on point here. One thing you can do to confirm, is to add something like console.log( btcArr ) and that should show you whether you're getting anything back.

I set up a not too different demo that should that once the ajax callback successfully updates the value, it never goes back to 600, showing that indeed the value does get changed in the callback and the new value is available outside the ajax callback.

The ajax code I used is:

function getRate() {
    var gafa = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=100&q=";
    var url = gafa + encodeURI('http://news.yahoo.com/rss/sports/')+"&callback=?";
    $.getJSON(url, function(data) {
        //var btcArr = JSON.parse(data, true);
        var xData = data.responseData.feed.entries
        //btcusd = btcArr["last"];
        btcusd = xData.length;;
        //This will give me the correct value
        console.log(btcusd);
    });
}

The rest of the code is yours: WORKING JSFIDDLE DEMO

PeterKA
  • 24,158
  • 5
  • 26
  • 48