0

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.

Dan Twining
  • 640
  • 4
  • 17
  • 30

4 Answers4

3

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.

lomaxx
  • 113,627
  • 57
  • 144
  • 179
1

your ajax url needs to be the web url of emailcheck.php not a relative system path using ./

var EmailCheckRes = $.ajax({

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

    }).responseText;

EDIT : While it is not the optimal solution to switch to a synchronous server request, you might just set the ajax option async: false which will make the browser wait for the response to continue, which should eliminate your issue. Also I would recommend switching to an absolute path, and/or removing the ./ from the front of your relative path. I have reflected this option addition to my example code.

jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
  • Hi, Thanks for response. I've restructured things but doing the return true / false within the success function seems to cause some scope issues as it only returns true / false from the ajax function, not from the overall checkemail function. At the moment checkemail() is returning true all the time and the form is submitting. As a side note, i don't think changing the URL from relative to absolute makes any difference. – Dan Twining Jan 10 '11 at 01:11
  • @Dan Twining I've adjusted my answer to take a different approach because you do not wish to restructure your code to take advantage of the `success` callback – jondavidjohn Jan 10 '11 at 03:07
  • Thanks! Setting to sync worked perfectly. I've learnt something here. – Dan Twining Jan 10 '11 at 11:39
1

You need to restructure your code. Most of the AJAX calls are async, meaning the flow of the code goes without waiting for the call to be completed.

Meaningfully, you need to change:

function checkmail() {
    var checkThis = Ajax();

    if (checkThis) {
        DoSomething();
    }
    else {
        DontDoSomething();
    }
}

for:

function checkmail() {
    Ajax.success = function(checkThis){
        if (checkThis) {
            DoSomething();
        }
        else {
            DontDoSomething();
        }
    };

    Ajax.error= function(){
        ReportSomeError();
    };

    Ajax();
}

Applied to your code, it may go something like this:

function checkemail () {
    var EmailFromForm = $("#lostemail").val(),

    $.ajax({
        type:"POST",
        cache:false,
        url:"./scripts/passreset/emailcheck.php",
        data:"Email="+EmailFromForm,
        dataType:"text",
        success:function(EmailCheckRes){
            if (EmailCheckRes == "true") {
                alert("Should say true:  " + EmailCheckRes);

                /* You cannot longer "return" this value, add code to do
                 * what you need done
                 */
                return true;
            }
            else {
                $("#ErrorMsg").html("Your email address is either invalid or not found.");
                alert("Should say false:  " + EmailCheckRes);

                /* You cannot longer "return" this value, add code to do
                 * what you need done
                 */
                return false;
            }
        },
        error:function(){
            $("#ErrorMsg").html("There was an AJAX communication error.");
        }
    });
}
Ast Derek
  • 2,739
  • 1
  • 20
  • 28
  • Thanks Derek, While I understand about using the success call, i'm still unsure as to how to actually return something out of the ajax function that can be used externally. It seems to me that changing to a synchronous ajax function is the only way this can be, done but i'd love to be told otherwise. – Dan Twining Jan 10 '11 at 11:43
  • You don't return anything, I just leave those there to represent success and error. – Ast Derek Jan 19 '11 at 00:15
  • You don't return anything, I just leave those there to represent success and error. Normal code flow makes other areas to wait for the script response; as with async AJAX, you need to simulate that waiting time. As an example, you can add a class to the email field (`class="invalid"`), then run the AJAX call; when the script returns you either leave the `"invalid"` class, or switch to a `"valid"` class. To validate the field, check for the `"valid"` class. – Ast Derek Jan 19 '11 at 00:21
0

I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.

jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.

I tried many, many, many different methods, but in the end, the answer I needed was at this stackoverflow page: JQuery - Storing ajax response into global variable

Thanks to contributor Charles Guilbert, I am able to get data into my variables, even when my page first loads.

Here's an example of the working script:

jQuery.extend
(
    {
        getValues: function(url) 
        {
            var result = null;
            $.ajax(
                {
                    url: url,
                    type: 'get',
                    dataType: 'html',
                    async: false,
                    cache: false,
                    success: function(data) 
                    {
                        result = data;
                    }
                }
            );
           return result;
        }
    }
);

// Option List 1, when "Cats" is selected elsewhere
optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");

// Option List 1, when "Dogs" is selected elsewhere
optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");

// Option List 2, when "Cats" is selected elsewhere
optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");

// Option List 2, when "Dogs" is selected elsewhere
optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");
Community
  • 1
  • 1
CityPickle
  • 131
  • 1
  • 1