0

Why is this not working?

var names;

$.ajax({
     type : 'POST',
     url : postUrl+"/admin/returnUserJSON",
     success : function(data){
          names = data;
     }
});

console.log(names);

Problem: Console.log is returning undefined.

intelis
  • 7,829
  • 14
  • 58
  • 102

4 Answers4

7

As $.ajax call is asynchronous, the console.log will be called before names=data line will be executed (as it's a part of $.ajax callback function, which will be called only after the server's response). Hence it will output undefined.

You can fix it two ways: either move your output into the callback function...

function(data){
  names = data;
  console.log(names);
}

... or make use of Promise interface:

$.ajax({
     type : 'POST',
     url : postUrl+"/admin/returnUserJSON",
     success : function(data){
          names = data;
     }
}).then(function() { console.log(names); });
raina77ow
  • 103,633
  • 15
  • 192
  • 229
2

You need to move your console.log into the success handler.

 success : function(data){
      names = data;
      console.log(names);
 }
mrk
  • 4,999
  • 3
  • 27
  • 42
2

Your AJAX request has not finished firing by the time console.log is being executed.

If you move the console.log to the success callback, you will get the data correctly.

var names;

$.ajax({
     type : 'POST',
     url : postUrl+"/admin/returnUserJSON",
     success : function(data){
          names = data;
          console.log(names);
     } 
});

I would suggest reading up on asynchronous javascript programming!

Paul Armstrong
  • 7,008
  • 1
  • 22
  • 36
1

AJAX request fires after the page has already been loaded, so that's why you get the error. When you print the variable to the console, the variable does not exists.