0

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

NamedArray
  • 773
  • 3
  • 10
  • 25
  • 1
    Your ajax function is **asynchronous**. – Pointy Nov 08 '17 at 21:28
  • 2
    Because the ajax takes some time to finish, but everything after it will run immediately. Just call another function at the end of your success callback to do whatever you want to do with the data. – Chris Nov 08 '17 at 21:29
  • 2
    You can call whatever function needs to process that array from within the success function, passing the array as a parameter – IrkenInvader Nov 08 '17 at 21:32
  • 2
    $.ajax is a asynchronous function. the console.log function is firing before the code in your success callback function, which is why your array is empty. – link0047 Nov 08 '17 at 21:32
  • That all worked. Thank you for helping me make sense of it! – NamedArray Nov 08 '17 at 21:39

1 Answers1

-1

it hits this line of code 1st;

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

Asynchronous Javascript before the Ajax call returns processes

Nick Timmer
  • 425
  • 2
  • 12