Assigning jQuery ajax response text to variable constanty returns null

Dan Twining picture Dan Twining · Jan 10, 2011 · Viewed 13.4k times · Source

hopefully one of you on this great site can help. I'm having issues with assigning a variable to a jQuery ajax call response text.

I have a form which when submited runs my "checkemail" function to varify the email address can be found in a database. If it's found, the responseText == "true", else "false". This works fine, and can be seen ok using Firebug....but the actual variable the response text should be assigned to is constantly showing "", and therefore causing the function to return false all the time.

        function checkemail(){

            var EmailFromForm = $("#lostemail").val();

            var EmailCheckRes = $.ajax({

            type        : "POST",
            cache       : false,
            url         : "./scripts/passreset/emailcheck.php",
            data        : "Email="+EmailFromForm,
            dataType        : "text",

      }).responseText;


            if (EmailCheckRes == "true")
            {
                alert("Should say true:  " + EmailCheckRes);
                return true;
            }
            else
            {
                $("#ErrorMsg").html("Your email address is either invalid or not found.");
                alert("Should say false:  " + EmailCheckRes);
                return false;
            }   

        }   

If anyone has any pointers as to what i'm doing wrong it'd be greatly appreciated.

Answer

lomaxx picture lomaxx · Jan 10, 2011

The problem is that the $.ajax method is getting executed async so the checkemail function is returning before your ajax request is completed.

The flow of your application is not linear and therefore your return value from checkmail will not reflect the response returned from your ajax request.

You'll need to restructure your code to take a callback and execute it when your ajax request is complete.