1

Below is my code in a JavaScript file that is included in an HTML file. When I console.log msg I can see there are 100 items in the array (see screenshot), however dataArray is still empty after the last console.log(dataArray).

I don't get any errors or things like that so it's hard for me to debug this.

function loadPosts() {
  var dataArray = new Array();
  var root = 'https://jsonplaceholder.typicode.com';
  $.ajax({
    url: root + '/posts/',
    method: 'GET',
    success:function(msg){
      dataArray = msg;
    }
  });

  console.log(dataArray);
} 

window.onload = loadPosts;

console response

halfer
  • 19,824
  • 17
  • 99
  • 186
roy-willemse
  • 325
  • 1
  • 4
  • 14
  • 1
    Possible duplicate of [AJAX asynchronous call -- can't return data with callback?](https://stackoverflow.com/questions/14732123/ajax-asynchronous-call-cant-return-data-with-callback) – Redu Aug 05 '17 at 12:32
  • your arrayList have nested ArrayList . You have to pare it to get actual array, Change this `dataArray = msg;` to `dataArray = msg.d;` – Mohd Aman Aug 05 '17 at 12:34
  • try async:false. – nilesh Aug 05 '17 at 12:40
  • You are setting `dataArray` to reference `msg`, and the initial array is thrown out. _You aren't setting the actual elements of the array to anything._ – clabe45 Aug 05 '17 at 12:42
  • The code section seems to be ok. It is doing what it was created for. Actually the `loadPosts()` function does nothing except fetching the data using ajax call. You didn't returned the `dataArray` in that function. Didn't used the `dataArray` for any purpose. – Sinha Aug 05 '17 at 12:42
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Hassan Imam Aug 05 '17 at 12:47

4 Answers4

3

Your console.log is executed before the AJAX request's success handler is called, otherwise it looks correct. You can add a console.log(dataArray) after you assign dataArray = msg; in the callback to see it.

timotgl
  • 2,865
  • 1
  • 9
  • 19
2

AJAX is asynchronous by nature, so what is happening is you are executing:

  1. Ajax call
  2. console.log(dataArray)
  3. Success callback

For the desired output you should move your console log into the success handler:

function loadPosts() {
    var dataArray = new Array();
    var root = 'https://jsonplaceholder.typicode.com';
    $.ajax({
      url: root + '/posts/',
      method: 'GET',
      success:function(msg){
        dataArray = msg;
        // act on data array
        console.log(dataArray);
      }
    });
} 

I would also recommend moving from the success/error callbacks to Promises, since the callbacks are deprecated and removed as of jQuery 3. This would change your code like so:

function loadPosts() {
    var root = 'https://jsonplaceholder.typicode.com';
    return $.ajax({
      url: root + '/posts/',
      method: 'GET'
    });
}

loadPosts().then(function(data) {
    // resolve promise handler
    // do something with your data
    console.log(data);
}, function(err) { 
    // rejected promise handler (failure)
    console.error(data);
});

For more info:

jQuery Ajax Documentation

Promise Spec

Dan D
  • 2,493
  • 15
  • 23
1

Check this code below :

function loadPosts() {
  var dataArray = [];
  var root = 'https://jsonplaceholder.typicode.com';
  $.ajax({
    url: root + '/posts/',
    method: 'GET',
    success:function(msg){
      console.log('First');
      dataArray = msg;
    }
  });
  console.log('Second');
  console.log(dataArray);
} 
window.onload = loadPosts;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

you will see that the order of execution. If you need to treat dataArray after his assignment, in success callback, you need to call a function and pass as argument the new dataArray.

Jean-louis Gouwy
  • 182
  • 3
  • 10
0

console.log is executed before ajax call is completed. so make asynchronous request.

 function loadPosts() {
  var dataArray = new Array();
  var root = 'https://jsonplaceholder.typicode.com';
  $.ajax({
    url: root + '/posts/',
    method: 'GET',
    async:false,// <--
    success:function(msg){
      dataArray = msg;
    }
  });
   console.log(dataArray);
} window.onload = loadPosts;
nilesh
  • 191
  • 5
  • 20