Image

Imageadcott wrote in Imagejavascript

AJAX race conditions

This looks so stupidly simple, but I can't figure it out and it's really holding me up.



Using XMLHttpRequest I can make a function to process the contents of another file, but I can't find a way to make a function to return the contents of another file.



For example, this works:

var xmlhttp;

function getFile() {
	if (xmlhttp) {
		xmlhttp.open("POST", "file.txt",true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				alert(xmlhttp.responseText);
			}
		}
	}
}

window.addEventListener('load',function(ev) {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
	getFile();
}, false);




whereas this wont:

var xmlhttp;

function getFile() {
	var response = "no data";
	
	if (xmlhttp) {
		xmlhttp.open("POST", "file.txt",true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				response = xmlhttp.responseText;
			}
		}
	}
	
	return response;
}

window.addEventListener('load',function(ev){
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
	
	alert(getFile());
	
}, false);




It's obviously a race condition - as XMLHttpRequest runs as a seperate thread the getFile() function is exiting before the inner function has completed and will always return "no data".



Problem is, I can't think of a way to work around it. Can anyone help me out? I'm sure this must be a reasonably common problem.