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.
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.
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); });
You need to move your console.log into the success
handler.
success : function(data){
names = data;
console.log(names);
}
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!
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.