Hi all,

I'm having some problems with a piece of ajax code. I have a page with a couple of forms, all with the same name. On submit, I want to use Ajax to send the form. For now, I only want to output the content of a simple txt file into a div on my page, just so I know it works.
Though, whatever I try, the readystate of the request stays 0. What am I doing wrong?

window.onload = initAll;
var xhr = false;

function initAll(){
	var allForms = document.getElementsByName('edit_module_form');
	for(var i=0; i < allForms.length; i++){
		allForms[i].onSubmit = submitForm;
	}
}

function submitForm()
{ 
	if (window.XMLHttpRequest){
		xhr=new XMLHttpRequest();
	}
	else{
		xhr=new ActiveXObject("Microsoft.XMLHTTP");
	}
    
	if(xhr){
		xhr.onreadystatechange = send_form;
		xhr.open(GET, "result.txt",  true); 
   		xhr.send(null); 
	}
	return false;   
}

function send_form(){
	if (xhr.readyState == 4) {
		if (xhr.status == 200) {
			var outMsg = xhr.responseText;
		}
		else {
			var outMsg = "There was a problem with the request " + xhr.status;
		}
		alert(outMsg);
	}
}

shouldn't line 7 be:
allForms.onSubmit = submitForm();

instead of:
allForms.onSubmit = submitForm;

The function is added the right way, because if I put any alerts in the submitForm function, they show up correctly.
It goes wrong when checking the readystate...

Typically you see readyState == 0 when you are "file browsing", ie relying on the operating system to serve the files rather than employing a proper HTML server.

If you use a desktop PC as your development environment, then the most realistic option is to install Apache or Microsoft IIS. Some people swear by XAMPP, which is an all-in-one installer for Apache, MySQL, PHP and Perl.

Airshow

I tried Xampp as well as an online host, but neither work correct..

Eric,

Aha, then it's the javascript .....

Try attaching the onreadystatechange handler as an anonymous function, rather than a providing a reference to it, like this:

function submitForm()
{ 
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	}
	else {
		xhr=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(xhr){
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					var outMsg = xhr.responseText;
				}
				else {
					var outMsg = "There was a problem with the request " + xhr.status;
				}
				alert(outMsg);
			}
		};
		xhr.open(GET, "result.txt",  true); 
   		xhr.send(null); 
	}
	return false;   
}

This way, the handler sees xhr in a closure formed by the outer function.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.