0

Given the following index.html

<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>

var nodes = [];

  $.get("mappings/Actor.hbm.xml", function(d){    
    nodes.push({"id":nodes.length,
        "label":$(d).find("class").attr("table"),
        "x":0,
        "y":0
        });            
}); 
    console.log(nodes)  

</script>

And the following outtake of the xml

<hibernate-mapping>
    <class name="nl.sander.mieras.localhost.sakila.Actor" table="actor" catalog="sakila">

The console shows an empty array [] when I put the console.log(nodes) outside the method body. It seems as if the push of data into the var nodes array is not persisted outside the scope of the method body.

How do I persist/store/save/hold (don't know the technical js term) the pushed data into the var nodes array, in order to be able to console.log(nodes) and see the object instead of an empty array?

Sander_M
  • 1,109
  • 2
  • 18
  • 36
  • Are you quite certain that the push statement is executing at all? The push will only execute if the request succeeds. As a side note, the inconsistent tabbing makes this code very difficult to read. – rmehlinger Mar 19 '16 at 00:14
  • @rmehlinger Thanks for pointing out the horrible tabbing, it had to do with the way I pasted the code in the question. I will edit it. – Sander_M Mar 19 '16 at 01:08
  • @Roamer-1888 Didn't find this answer on my own, but yes this is the answer to my question. Thanks for indicating it as a duplicate. – Sander_M Mar 19 '16 at 01:08
  • @Sander_M, unfortunately you need to virtually know the answer in order to find that question. It's an intractable conundrum. – Roamer-1888 Mar 19 '16 at 01:28

1 Answers1

3

It looks like you're printing nodes before your AJAX request returns. Remember, JavaScript is asynchronous, so your callback is not immediately invoked. Try setting a timeout and then printing nodes:

setTimeout(function () { console.log(nodes) }, 2000);

Whatever you need to do with the response of your AJAX call should be handled in the callback for the exact issue you were experiencing; there's no other way to guarantee that the data is available yet.

Calvin Belden
  • 3,114
  • 1
  • 19
  • 21