0

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);
    });

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

just remove the last console.log, result's not meant to be defined there
0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.