0

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);
	}
}

Edited by eric8990: n/a

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by Airshow
0

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...

0

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

Edited by Airshow: n/a

0

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

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.