Search code examples
javascriptjqueryjsonxmljstree

Why is my Array behaving differently outside of an AJAX function? (populating jsTree)


Long story short, I'm creating a JSON-like array for jsTree. What I don't understand is why the array is perfect for my needs inside the AJAX success function, but broken outside of that function. Check out the screenshot from my console dump, you can see the differences. Why is it different inside of the function vs. outside of the function?

Essentially, I can't do what I need to do unless it's in the perfect format: (myAry inside the function)

What gives, man?

var myAry = [];

$.ajax({
type: "GET",
url: "parents.xml",
dataType: "xml",
success: function(xml) {

    $(xml).find('group').each(function() {

      myAry.push({
        "id": $(this).find('GroupID').text(),
        "parent": "#",
        "text": $(this).find('GroupName').text(),
      });


    }); //end each loop

      //this array is PERFECT
      console.log(myAry);

      } //end success function
  }); //end ajax GET

  //THIS ARRAY IS BORKED
  console.log(myAry);

xml:

 <groups>
    <group>
        <GroupID>1</GroupID>
        <GroupName>Instructional Assistant</GroupName>
    </group>
    <group>
        <GroupID>2</GroupID>
        <GroupName>Technician</GroupName>
    </group>
    <group>
        <GroupID>3</GroupID>
        <GroupName>HR Specialist</GroupName>
    </group>
</groups>

enter image description here


Solution

  • it hits this line of code 1st;

    //THIS ARRAY IS BORKED console.log(myAry);

    Asynchronous Javascript before the Ajax call returns processes