1

I'm trying to print through innerHTML some data got with the ajax call, but the global array elements it is not accesible in the done() promise.It is indeed undefined. Why does that happen?

<html>
<head></head>
<body>
    <script src ="jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            var elements = document.getElementsByClassName("wind");

            for(i=0;i<elements.length;i=i+1){

                $.ajax({
                    type:"GET",
                    url:"http://api.openweathermap.org/data/2.5/weather?q="+elements[i].innerHTML+"&appid=7876b25bdca1397553df39ef3ea05fd1",
                    dataType: "json"
                }).done(function(data){
                    elements[i].innerHTML = data.wind.speed; //elements[i] is undefined
                });

                //elements[i].innerHTML     here elements[i] is OK but I don't have access to "data"

            }

        });
    </script>

    <div class="wind">Venice,it</div>
    <div class="wind">Rome,it</div>

</body>

sguci
  • 15
  • 2
  • _"but the global array elements it is not accesible"_ It is accessible, but `i` is out of bounds when the `elements[i].innerHTML = ...` part is executed. – Andreas May 01 '17 at 14:27
  • Thank you. Sorry for the duplicate but I didn't figure it was an index scope problem. The best solution is to use for each – sguci May 01 '17 at 14:44

1 Answers1

0

Try using the success setting rather than done. This will activate when the request is successful and it returns the data.

$.ajax({
    type:"GET",
    url:"http://api.openweathermap.org/data/2.5/weather?q="+elements[i].innerHTML+"&appid=7876b25bdca1397553df39ef3ea05fd1",
    dataType: "json",
    success: (function(data){
        elements[i].innerHTML = data.wind.speed; 
    }),
});  
Naltroc
  • 989
  • 1
  • 14
  • 34
  • It gives me the same error – sguci May 01 '17 at 14:35
  • As Andreas mentioned, this looks more like a variable scope issue. You could also try declaring elements using 'let', as in `let elements = `, but that's just what comes off the top of my head. – Naltroc May 01 '17 at 14:37