views:

46

answers:

1

XmlHttpRequest works through callbacks. So how can I return a value? I tried to set a global variable, but that doesn't seem to be working.

var response = null; // contains the most recent XmlHttpRequest response

// loads the info for this username on the page
function loadUsernameInfo(username) {
    getUserInfo(username);
    var profile = response;
    if (profile) {
        // do stuff
    }
    else {
        indicateInvalidUsername(username);
    }
}

getUserInfo() can't return a result, because of the callback:

function getUserInfo(username) {
    var request = createRequest();
    request.onreadystatechange = userObjFromJSON;
    var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
    var url = "url.php?url=" + twitterURL;
    request.open("GET", url, true);
    request.send(null);
}

The callback:

function userObjFromJSON() {
    if (this.readyState == 4) {
        alert(this.responseText);
        response = this.responseText;
    }
}

How can I get the response back to loadUsernameInfo()?

A: 

You can do synchronous requests, though it is not recommended - the A is for Asynchronous... But the general idea to implement this correctly would be:

var response = null; // contains the most recent XmlHttpRequest response

// loads the info for this username on the page
function loadUsernameInfo(username) {
    getUserInfo(username, onLoadUsernameComplete);
}

function getUserInfo(username, oncomplete) {
    var request = createRequest();
    request.__username = username;
    request.onreadystatechange = oncomplete;
    var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
    var url = "url.php?url=" + twitterURL;
    request.open("GET", url, true);
    request.send(null);
}

function onLoadUsernameComplete(req) {
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            var profile = req.responseXML;
            if (profile) {
                // do stuff
            }
            else {
                indicateInvalidUsername(req.__username);
            }
        }
    }
}
consultutah
You'll need somehow to capture the value of `username` if you're going to use it in `onLoadUsernameComplete`
Kyle Butt