5

I have this code for make some request to my server:

function myAjaxCheck(token) {
        $.ajax({
            type: 'POST',
            url: 'auth.php',
            data: {
                token: token,
            },
            dataType: 'json',
            success: function (data) {
                if (data.auth == 'OK') {
                    alert ('ok');
                    }
                } else {
                    alert('Error: ' + data.auth);
                }
            }
        }).done(function (data) {
            return data;
        });
    }

So, i need to pass the returned data into a variable like:

Var MyVariable = myAjaxCheck(token);
console.log(MyVariable);

at console:

undefined

Where is the problem, is supposed to data will returned when done, but isn't.

0

3 Answers 3

9

By default, an ajax() request is asynchronous so the call to ajax() will usually return before the request completes. You could make use of a callback function instead.

function myAjaxCheck(token, callback) {
        $.ajax({
            type: 'POST',
            url: 'auth.php',
            data: {
                token: token,
            },
            dataType: 'json',
            success: function (data) {
                if (data.auth == 'OK') {
                    alert ('ok');
                    }
                } else {
                    alert('Error: ' + data.auth);
                }

                callback(data);
            }
        });
    }

var myVariable; 
 myAajxCheck(token, function(returnedData){ //anonymous callback function
    myVariable = returnedData;
    console.log(myVariable);
 });

If you absolutely must, you could use async: false inside the call to ajax().

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

Comments

0

Please see Waiting for $.post to finish.

Basically, it is better to use callbacks. Your variable seems to be undefined, because the code returning it to the console is executed before the AJAX request is finished.

Comments

0

Because you are expecting a value to be returned immediately. You are using asynchronous XHR, so, the function will return (undefined in this case) before the XHR has a chance to finish and return its value.

1 Comment

Ok, but what is the solution? Please add more to your answer to make it better

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.