0

I am getting "undefined" when making an HTTP get request, but only the first time I make the request. The second time and on the code seems to work perfectly fine.

Below is my code:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        let myData = "";
        let dataTest = "";
        $(document).ready(function(){
            $("button").click(function(){
                $.get("https://api.coinmarketcap.com/v1/ticker/ethereum/", function(data, status){
                    myData = data[0];
                });
                document.getElementById("p1").innerHTML = (myData.price_usd);
            });
    });
    </script>
</head>
<body>
    <p>If you want to get the price of Ethereum, press the following button:</p>
    <button>Submit</button>
    <p id="p1">
    </p>
</body>

  • Read the answers in [this](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable) SO question. – Jeroen Heier Feb 27 '18 at 04:54

2 Answers2

2

Put the assignment into the innerHTML in the get asynchronous request's callback. You don't know when your call will be finished, so why you need to write it in the callback. at the first time, you assign then the call is finished

$(document).ready(function(){
      $("button").click(function(){
            $.get("https://api.coinmarketcap.com/v1/ticker/ethereum/", function(data, status){
                  myData = data[0];
                  document.getElementById("p1").innerHTML = (myData.price_usd);
            });                    
      });
});
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        let myData;
        let dataTest;
        $(document).ready(function(){
            $("button").click(function(){
                $.get("https://api.coinmarketcap.com/v1/ticker/ethereum/", function(data, status){
                    myData = data[0];
                    logg();
                });

            });
        });
      function logg(){
        document.getElementById("p1").innerHTML = (myData.price_usd);
      }
    </script>
</head>
<body>
    <p>If you want to get the price of Ethereum, press the following button:</p>
    <button>Submit</button>
    <p id="p1">
    </p>
</body>

Because its async and when ever it is finished assigning data[0] to myData, THEN you will change the innerHtml of document.