JavaScript scope question

Status
Not open for further replies.

AliceWonder

Ars Legatus Legionis
24,239
I do not usually code in JavaScript.

ajaxpath is a global and emailFocus is an earlier defined function. Neither of those are at issue but they are referenced so that's what they are.

Code:
function ajaxEmail(address) {
    "use strict";
    var postdata, r;
    r = 1;
    postdata = { email: address };
    $.ajax({
        type: 'POST',
        url: ajaxpath,
        data: postdata,
        dataType: 'text',
        success: function (text) {
            if (text === 'invalid') {
                emailFocus('You must enter a valid Email address.');
                r = 0;
            }
            if (text === 'used') {
                emailFocus('The e-mail address you entered is already in use.');
                r = 0;
            }
        },
        error: function () {
            window.alert('I had trouble communicating with the server. Please try again later.');
            r = 0;
        }
    });
    if (r === 0) {
        return false;
    }
    return true;
}

The problem is the function never returns false because when r is modified inside the jQuery.ajax call it is local to that scope.
I know why the function never returns false, other than doing something hackish like adding an attribute to a node in the dom and reading it from outside the jQuery.ajax scope, I just don't know how to get the function to return false under one of the conditions where I want it to.

I just don't know JavaScript well enough, and this is something where stack exchange that usually helps me, I can't find a similar question at least not that I recognize would be a solution.

Thanks for suggestions.
 

Marco

Ars Scholae Palatinae
1,346
Don't feel dumb :) Asynchronous operations puzzle most people when first confronted with them.

Since you're using jQuery, you could use deferred objects to handle AJAX responses. The $.ajax() method itself returns a deferred object, so rather than your function returning true/false you could just return the AJAX object itself and use the done/fail methods that will fire when the AJAX call completes:

Code:
function ajaxEmail(address) {
    "use strict";
    var postdata;
    postdata = { email: address };
    return $.ajax({
        type: 'POST',
        url: ajaxpath,
        data: postdata,
        dataType: 'text'
    });
}

ajaxEmail(emailaddress)
    .done(function(text) {
        if (text === 'invalid') {
            emailFocus('You must enter a valid Email address.');
        } else if (text === 'used') {
            emailFocus('The e-mail address you entered is already in use.');
        }
    })
    .fail(function () {
        window.alert('I had trouble communicating with the server. Please try again later.');
    });
 
Status
Not open for further replies.