0

I'm struggling to get access to array data outside of my ajax request.

This is the code I've got:

test.php contains:

echo json_encode($staffID);

JQuery is :

var id = [];
$.ajax({
    type: "POST", cache: false, dataType: 'json',
    url: "test.php",    
    success: function(data) {
    id = data;
    console.log (id)  //SHOWS ARRAY VALUES
    }
});

console.log (id)  //DOESN'T SHOW ANYTHING

The console log output within the ajax request shows:

["1234", "2468", "3579", "0864"]

My aim is to run a couple of ajax requests and return a total of two different arrays. Once I can access the array data outside of the ajax result I will be able to check if other values are in the returned array data.

How do I access the array id outside of the ajax request ?

EDIT: I'm trying to use the following :

function foo(callback) {

    $.ajax({
        url: '...',
        success: function(response) {
           return callback(null, response);
        }
    });
}

var result = foo(function(err, result){
          if (!err)
           console.log(result);    
}); 

console.log(result); does return the correct results, but is there any way I can access that as an array elsewhere in the script ?

Thanks

Tom
  • 1,436
  • 24
  • 50
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Mar 10 '17 at 15:15
  • Hi. Not sure how this is a duplicate. I can get the results in the success function. I'm struggling to get access to it as an array outside of the ajax request. – Tom Mar 10 '17 at 15:19
  • It's the exact same problem. Read the accepted answer to understand what's going on. Basically, your last line is running before you get the response from the AJAX call so you have to do your logic from the callback. – mafafu Mar 10 '17 at 15:21
  • And also follow the link at the top of the accepted answer – Andreas Mar 10 '17 at 15:22
  • Thanks for the patience on this.. I now see what you mean.. But I'm still not getting the result I was expecting. I'll update my question. – Tom Mar 10 '17 at 16:57

1 Answers1

0

It is normal that you do not see the data. $.ajax function send send requests asynchronously. So work your code looks like this:

  1. Call to $.ajax function
  2. Call console.log
  3. Ajax gets response and call success function

Simple, $.ajax doesn't block further execution of code while waiting for a response. If you wont block then you must set async $.ajax parameter to false:

var id = [];
$.ajax({
    type: "POST", cache: false, dataType: 'json',
    url: "test.php",    
    async: false,
    success: function(data) {
        id = data;
        console.log (id)  //SHOWS ARRAY VALUES
    }
});

console.log (id);

But this parameter stop the browser working until response will not come.

On the end, You should manipulate HTML, data or anything else in success function. This is the best way.