Reputation: 1119
Why can’t I assign ajaxResult to result? console.log(result); works correctly which is inside the success option and appears second in the console. but result of the last of console.log(result); is undefined and first appears in the console. what is wrong with this?
$(function () {
var result;
$.ajax({
type: 'POST',
url: 'GelinlikSet',
dataType: 'json',
success: function (ajaxResult) {
result = ajaxResult;
console.log(result);
}
});
console.log(result);
});
Upvotes: 0
Views: 158
Reputation: 4623
The second console.log is being executed immediately after the ajax call, before the success function gets called because it's Asynchronous (ie, The A in Ajax).
Upvotes: 0
Reputation: 155915
result
should be set to ajaxResult
after the success
callback runs.
The AJAX callback won't be able to come back until the current thread is finished (i.e. the thread that is calling $.ajax
and console.log
).
If you need to perform some action with the result, you will have to do it from the success
callback.
Upvotes: 2
Reputation: 12078
The console.log outside the ajax call is being executed before the ajax returns.
The console.log in the success is where it should be to log something of the ajax.
Upvotes: 1