Sign in to follow this  
Spidy

[web] AJAX: Having a variable problem

Recommended Posts

Hello, all. I'm working with some AJAX, attempting to grab the value returned by a script and do some things based on that value. Here's my generalized XMLHttpRequest code:
function doAjax(url) {
	var ajaxRequest;
	try {
		ajaxRequest = new XMLHttpRequest();
	} catch (e) {
		try {
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your Bowser is broken.");
				return false;
			}
		}
	}
	// receive data sent from the server
	ajaxRequest.onreadystatechange = function() {
			if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
				var response = ajaxRequest.responseText;
				return response;
			}
	}
	ajaxRequest.open("GET", url, true);
	ajaxRequest.send(null);
}
And I'm calling it by doing this:
var myVariable = doAjax('myscript.cgi');
But for some reason, myVariable is always undefined. ajaxRequest.responseText will be 0, which is what it's supposed to be, but myVariable is undefined. Does anyone know why this is, and how I could fix it? Thanks, Spidy

Share this post


Link to post
Share on other sites
Your doAjax function doesn't return anything, that's why the var is null. OnReadyStateChange fires when the data arrives (not when the function returns).

One thing you could do is a callback when the data arrives.

eg, pass callback_function as a string into your doAjax function
var response = ajaxRequest.responseText;
setTimeout(callback_function + "(" + response + ")", 0);


Hope that helps

Share this post


Link to post
Share on other sites
You have failed to understand the "asynchronous" bit of AJAX.


return response;


Will return from the anonymous function in onreadystatechange, NOT the original function doAjax, which will return immediately.

The onreadystatechange function will be called once the request is complete, which will be later, after you've already done what you're trying to do.

Personally I'd add a second parameter to doAjax() to store a function which is called upon successful completion, e.g.

function doAjax(url, completeFunc) {
// ...
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var response = ajaxRequest.responseText;
completeFunc(response);
}


Which uses completeFunc as a closure to remember what function to call when the request is complete.

Mark

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this