views:

42

answers:

3

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);
    });
+1  A: 

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.

Chris
what is solution?
berotomanya
just remove the last console.log, result's not meant to be defined there
box9
+1  A: 

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.

bdukes
A: 

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).

DavidGouge