1

I have a jQuery function that uses Ajax. It always returns undefined and I can figure out why.

I notice that if I alert the variable registered in the $.post function it works, but does not if I try it outside.

function signup(){

    var username = $('#su-username').val();
    var password = $('#su-password').val();

    if(username!='' && password!=''){

        $.post("register.php", { user: username, pass: password }).done(function(response){

            if($.trim(response)=='1'){
                alert('Username Taken, Please choose another');
                var registered = 0;
            }else{
                var registered = 1;
            }

        });

    } else {

        alert('Username and password cannot be empty');
        var registered = 0;
    }
    return registered;
}
0

2 Answers 2

3

When you deal with asynchronous operations like AJAX it's recommended to make use of callback functions. For example:

function signup(callback) {

    var username = $('#su-username').val(),
        password = $('#su-password').val(),
        registered = 0;

    if (username != '' && password != '') {

        $.post("register.php", { user: username, pass: password }).done(function(response) {
            if ($.trim(response) == '1') {
                alert('Username Taken, Please choose another');
            }
            else {
                registered = 1;
            }

            // Delayed callback invocation after AJAX request
            callback(registered);
        });
    }
    else {
        alert('Username and password cannot be empty');
        callback(registered); // Immediate invocation of the callback function
    }
}

signup(function(ok) {
    if (ok) alert('Ok!');
    else alert('Not ok!');
});
Sign up to request clarification or add additional context in comments.

Comments

2

You are alerting out the variable before the code is finished running. Use an on success function instead from an AJAX call that when the value is returned you can use it.

At the moment, you are not waiting for the AJAX call to finish, you are continuing your code which is why you are getting undefined

2 Comments

That cant be true because if I try to register a user name that is already taken I get alert('Username Taken, Please choose another'); which is in the same if block as one that sets the registered variable?
well there you go, you need to process the code after recieving the value from the AJAX call, see the @dfsq answer for a good way to do that.

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.