0

Code in header:

<script>
  jQuery(document).ready(function() {
    jQuery('head').append('<script type="text/javascript" src="<?php echo esc_url( get_template_directory_uri() . '/js/price.js' ); ?>" />');
  });
</script>

price.js:

var usd, eur;
$( window ).load(function getPrice() {
    var usdApi = "https://api.bitcoinaverage.com/ticker/global/USD/last";
    var euroApi = "https://api.bitcoinaverage.com/ticker/global/EUR/last";

    $.getJSON(usdApi, function(data){
      usd = data;
    });
    $.getJSON(euroApi, function(data){
      eur = data;
    });

    alert('test'); //working

    $("#usd").append(usd);
    $("#euro").append("test"); //working
});

However, if I write in the js-console $("#usd").append(usd); it works. Seems that var usd is present, DOM and its content loaded before running the script.

chridam
  • 100,957
  • 23
  • 236
  • 235
user1201917
  • 1,360
  • 1
  • 14
  • 27
  • 2
    Restructure your code, because you're making AJAX Requests, read this [**AJAX SO Post**](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) on this issue. Remember, AJAX Is asynchronous; the `$('#usd').append()` is ran at a *different* time to which `usd` is defined. – MackieeE Jun 16 '14 at 14:55
  • That string you gave is invalid. `'...) . '/js/price.js' ); ?...'`. Your trying to use single quotes inside your single quotes, make sure to escape them with `\'` – Spencer Wieczorek Jun 16 '14 at 15:00
  • @MackieeE, thanks. Just moved .append() into ajax function. – user1201917 Jun 16 '14 at 15:06

0 Answers0