-1

I have the following script:

var myData;

$.ajax({
    url: "/foo.php",
    dataType : 'json',
    type: "POST",
    async: false
  })
  .done(function( data ) {
       myData = data;
  });

All I want to do is assign the data from the ajax response to myData and refer to this variable further down in my script. The above code seems to work but relies on async: false which I've read is not a good thing. If I comment this out (and therefore it uses the default async: true) nothing is assigned to myData.

I've read the following post jQuery ajax success callback function definition but can't adapt that so I can access the data in myData. I also note that question was asked in 2013 so not sure if it's still accurate or the right way to go about this?

How is this supposed to be done? I'm using jquery v1.11.1

Community
  • 1
  • 1
Andy
  • 5,142
  • 11
  • 58
  • 131
  • 1
    you are doing it the proper way, the problem is that you are trying to access `myData` before ajax finishes loading - if you access it in some kind of function etc. invoke it inside `done` callback when variable is ready – pwolaq Sep 12 '16 at 09:25
  • @pwolaq thanks for the info. Is there an example you could point me to where I can see how that's done? I'm quite new to jquery so trying to understanding where to place and call such functions. – Andy Sep 12 '16 at 09:35

1 Answers1

1

Ok so the following seems to work. I've removed async: false and added a function where I'm referring to the data from the ajax call.

$.ajax({
    url: "/foo.php",
    dataType : 'json',
    type: "POST"
})
.done(function( data ) {
   buildTree(data);
});

function buildTree(data) {
   console.log(data);
   // other code that needs 'data'
}

I assume this is correct based on what @pwolaq suggested.

Andy
  • 5,142
  • 11
  • 58
  • 131