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

6
  • 1
    Possible duplicate of AJAX asynchronous call -- can't return data with callback?
    – Redu
    Aug 5, 2017 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 5, 2017 at 12:34
  • try async:false.
    – nilesh
    Aug 5, 2017 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 5, 2017 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 5, 2017 at 12:42

4 Answers 4

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.

0
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

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.

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.