This may complicate your problem so feel free to interject, but using a third party Javascript library may help ease your burden slightly (as the commenter some mentioned). Prototype and JQuery both have ways of dealing with scope, such as the bind function in Prototype. Also, you won't have to write your own Ajax request code although I commend you for digging in and seeing how it works! Prototype classes can help with scope issues like you've described. You may want to refactor in order to use asynchronous Ajax requests though so that the browser doesn't have to wait as is the case with how you've written it. The following will popup your alert message and set the variable appropriately, although I haven't tested it for errors. It shows the basic concept though.
var TestClass = Class.create();
TestClass.prototype = {
MyVariable: null,
AjaxURL: "http://yourajaxurl.com/something.asmx",
DoAjaxCall: function() {
new Ajax.Request(this.AjaxURL,
method: 'get',
onSuccess: this.AjaxCallback.bind(this),
onFailure: this.DoSomethingSmart.bind(this));
},
AjaxCallback: function(returnVal) {
this.MyVariable = returnVal.responseText; //ResponseText or whatever you need from the request...
this.Popup(this.MyVariable);
},
DoSomethingSmart: function() {
//Something smart
},
Popup: function(message) {
alert(message);
}
};
var TestClassInstance = new TestClass();
TestClassInstance.DoAjaxCall();