0

I have this jQuery AJAX Call:

isEmailValid=test();

function test(){
var validateEmailURL='someURL';
.ajax({
    type: "POST",
    url: validateEmailURL,
    data: "email=" + email,
    success: function(msg){
        if(msg=='valid'){
             return true;
        }else if(msg=='error'){
             var errorMsg='Please enter a valid email.';
             return errorMsg;
        }
    }
});
}

Now, I am trying to read the value of isEmailValid and it always shows me 'undefined'. I know that the AJAX call is returning 'valid' or 'error' but I think that the return statement is not assigning the value back to isEmailValid. No matter what happens it keeps showing me isEmailValid as 'undefined'.

What do you think what's going on here and what can I do?

2 Answers 2

2

This is the nature of asynchronous calls. You have to provide a callback similar to what you pass in the success part, which will be called once the request is finished. In this callback you do your further processing:

isEmailValid=test(function(isValid) {
    alert(isValid);
});

function test(callback) {
    var validateEmailURL='someURL';
    $.ajax({
        type: "POST",
        url: validateEmailURL,
        data: "email=" + email,
        success: function(msg){
            if(msg=='valid'){
                callback(true);
            }else if(msg=='error'){
                 callback('Please enter a valid email.');
            }
        }
    });
}
1

$.ajax is asynchronous, so it will not a return a value to the calling object (unless you make it synchronous) So, you will most likely need to create a flag that the async response will set to tell you if the current email is valid or not.

var emailIsValidFlag = false;
var errorMsg='';

function test(){
    var validateEmailURL = 'someURL';           
    $.ajax({
        type: "POST",
        url: validateEmailURL,
        data: "email=" + email,
        success: function(msg){
            if(msg=='valid'){
                 emailIsValidFlag = true;
            }else if(msg=='error'){
                errorMsg='Please enter a valid email.';
                emailIsValidFlag = false;
            }
        }
    });
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.