Jump to content

AJAX call returning undefined in IE


lastlifelost

Recommended Posts

I'm trying to create a discussion board/comments thread. I've got it working in FF, Chrome, Safari and Opera, but IE keeps telling me the returned data is undefined. It's also not letting me send data to the server, or, if it is, it's not getting added to the posts.txt file.Here's what I'm working with right now:JavaScript

//compact xh script ////////////////////////////////////////////////////var xhrSubmitPost = makeRequest();function makeRequest() {	// IE7+, Chrome, Safari, Firefox, Opera	if (window.XMLHttpRequest) {		req = new XMLHttpRequest();	} else {			// IE5, IE6 		req = new ActiveXObject("Microsoft.XMLHTTP");	}	return req; }  // end compact xhrscript //////////////////////////////////////////////		//submitPost //////////////////////////////////////////////////////////function submitPost() {	var name = validField("name",true);	var message = validField("message",true);		alert (name + " " +message);	// Form verifier function.function validField(field,required) {	//Error Messages:  add or modify as needed.	var errors = {		name : "Name is required",		message : "Message is required"	};/*****************************************************************																				**				DO NOT EDIT BELOW THIS LINE					**																				*****************************************************************/	//loads email fields for verifying	Field = "#" + field; 								//creates jQuery-able id	vField = $(Field); 								//handles input fields	vStr = vField.val(); 								//grabs info to verify from input fields	vStr = vStr.replace(/^\s+|\s+$/g, '');		//removes leading/trailing spaces	alert (vStr);//	alert (errorExists);	//Throws errors for invalid input fields	if ( vStr === null || vStr === "" && required === true) {		if (!$("span.error:contains("+errors[field]+")").length) {			vField.after("<span class='error'>"+errors[field]+"</span>");		}		vStr = false;			} else {		$(".error").remove(":contains('"+errors[field]+"')");	}	return vStr;		//returns error code or valid info for mailing variables		}		if (name !== false && message !== false) {					myQuery = "?name=" + name + "&message=" + message;		doPosts(myQuery);	}} // end submitPost ////////////////////////////////////////////////////		function doPosts(myQuery) {	myUrl = "postRunner.php";	myQuery = (typeof myQuery == 'undefined') ? "" :myQuery;		xhrSubmitPost.open("GET", myUrl+myQuery, true);	xhrSubmitPost.onreadystatechange = useHttpResponse;	xhrSubmitPost.send();	function useHttpResponse() {		if (xhrSubmitPost.readyState == 4 && xhrSubmitPost.status == 200) { 			existingPosts = (typeof discLength != 'undefined' && discLength>=0 ) ? discLength + 1 : 0;			discLength = xhrSubmitPost.responseXML.getElementsByTagName("name").length-1;						while (existingPosts <= discLength) {				$("#posts").prepend("<div>"+xhrSubmitPost.responseXML.getElementsByTagName("name")[existingPosts].textContent + 											"\n<br>\n" + xhrSubmitPost.responseXML.getElementsByTagName("message")[existingPosts].textContent+"\n</div>");				existingPosts++;			}			existingPosts++;		}	}}

PHP:

<?php	$filename = 'posts.txt';	if ($_GET['name']) {		$handle = fopen($filename,'a');				$name = htmlentities($_GET['name']);		$message = htmlentities($_GET['message']);				$content = "\n<name>".$name."</name>\n\n<message>".$message."</message>\n";		fwrite($handle, $content);		fclose($handle);   	}		header("Content-type: text/xml");	echo '<?xml version="1.0" encoding="UTF-8"?>';	echo "\n<posts  xml:lang=\"EN\">\n";	readfile ($filename);	echo "\n\n</posts>\n";?>

What have I missed?EDIT:: Looks like the posting process is working now, but the returned data is still coming up undefined.

Link to comment
Share on other sites

First, find out if xhrSubmitPost is defined. In many modern compiled languages, you can call a function before it is defined. The javascript global space is different. It executes literally as the page downloads, which means that technically you may be calling makeRequest before it even exists. Simply reversing the sequence of the function and the call could end the problem. I'd look into it anyway. It's exactly the kind of thing browsers might differ on.Another possibility. IE is a bit touchy about XML documents. Have you tested xhrSubmitPost.responseText to see if it contains your downloaded document in string format? If it is, then IE is simply not recognizing the XML as XML.

Link to comment
Share on other sites

Caught your edit:If IE is receiving the response, but not recognizing the response as XML, try adding this line to doPosts after xhrSubmitPost.open and before xhrSubmitPost.sendxhrSubmitPost.setRequestHeader ("Accept", "text/xml");

Link to comment
Share on other sites

One fix is that you should replace this:myQuery = "?name=" + name + "&message=" + message;with this:myQuery = "?name=" + encodeURIComponent(name) + "&message=" + encodeURIComponent(message);Other than that, what exactly is it claiming is undefined? If it says that xhrSubmitPost.responseXML is undefined, see if the data is in xhrSubmitPost.responseText instead. You can just use alert to check that.

Link to comment
Share on other sites

One fix is that you should replace this:myQuery = "?name=" + name + "&message=" + message;with this:myQuery = "?name=" + encodeURIComponent(name) + "&message=" + encodeURIComponent(message);Other than that, what exactly is it claiming is undefined? If it says that xhrSubmitPost.responseXML is undefined, see if the data is in xhrSubmitPost.responseText instead. You can just use alert to check that.
Guy,I fixed myQuery as suggested. No dice. I used the alert(xhrSubmitPost.responseText) to find out that the data is showing up, but is not being read as XML.Here's a link to the active page, with the alert still turned on:http://seanosterhout.com/programmingfortheinternet/forum.phpI feel like we're getting closer, at least!
Link to comment
Share on other sites

I fixed myQuery as suggested. No dice.
That won't fix the return value, but it's necessary. If your message contains multiple words or certain characters then leaving out the encodeURIComponent will cause PHP to not retrieve the entire message.
Here's a link to the active page, with the alert still turned on:
That's odd, the headers look fine to have the returned value go into responseXML. Try sticking this after the open method:xhrSubmitPost.overrideMimeType('text/xml');
Link to comment
Share on other sites

That won't fix the return value, but it's necessary. If your message contains multiple words or certain characters then leaving out the encodeURIComponent will cause PHP to not retrieve the entire message.That's odd, the headers look fine to have the returned value go into responseXML. Try sticking this after the open method:xhrSubmitPost.overrideMimeType('text/xml');
Added - borked the IE more, actually. Now it doesn't return anything (visibly, at least). The alert doesn't show in IE anymore either. It this possibly because we're overriding the mime type now and IE's not registering responseText as a result?Everything is still working in the other browsers.Updated JS:
//compact xh script ////////////////////////////////////////////////////function makeRequest() {	// IE7+, Chrome, Safari, Firefox, Opera	if (window.XMLHttpRequest) {		req = new XMLHttpRequest();	} else {			// IE5, IE6 		req = new ActiveXObject("Microsoft.XMLHTTP");	}	return req; }  var xhrSubmitPost = makeRequest();// end compact xhrscript //////////////////////////////////////////////		//submitPost //////////////////////////////////////////////////////////function submitPost() {	var name = validField("name",true);	var message = validField("message",true);	// Form verifier function.function validField(field,required) {	//Error Messages:  add or modify as needed.	var errors = {		name : "Name is required",		message : "Message is required"	};/*****************************************************************																				**				DO NOT EDIT BELOW THIS LINE					**																				*****************************************************************/	//loads email fields for verifying	Field = "#" + field; 								//creates jQuery-able id	vField = $(Field); 								//handles input fields	vStr = vField.val(); 								//grabs info to verify from input fields	vStr = vStr.replace(/^\s+|\s+$/g, '');		//removes leading/trailing spaces	//Throws errors for invalid input fields	if ( vStr === null || vStr === "" && required === true) {		if (!$("span.error:contains("+errors[field]+")").length) {			vField.after("<span class='error'>"+errors[field]+"</span>");		}		vStr = false;			} else {		$(".error").remove(":contains('"+errors[field]+"')");	}	return vStr;		//returns error code or valid info for mailing variables		}		if (name !== false && message !== false) {					myQuery = "?name=" + encodeURIComponent(name) + "&message=" + encodeURIComponent(message);		doPosts(myQuery);	}} // end submitPost ////////////////////////////////////////////////////		function doPosts(myQuery) {	myUrl = "postRunner.php";	myQuery = (typeof myQuery == 'undefined') ? "" :myQuery;		xhrSubmitPost.open("GET", myUrl+myQuery, true);	//xhrSubmitPost.setRequestHeader("Accept", "text/xml"); 	xhrSubmitPost.overrideMimeType('text/xml');	xhrSubmitPost.send();	xhrSubmitPost.onreadystatechange = useHttpResponse;	function useHttpResponse() {		if (xhrSubmitPost.readyState == 4 && xhrSubmitPost.status == 200) { 			existingPosts = (typeof discLength != 'undefined' && discLength>=0 ) ? discLength + 1 : 0;			discLength = xhrSubmitPost.responseXML.getElementsByTagName("name").length-1;				alert ("xhrSubmitPost.responseText: \n" + xhrSubmitPost.responseText);						while (existingPosts <= discLength) {				$("#posts").prepend("<div>"+					xhrSubmitPost.responseXML.getElementsByTagName("name")[existingPosts].textContent +"\n<br>\n" +					xhrSubmitPost.responseXML.getElementsByTagName("message")[existingPosts].textContent+"\n</div>");				existingPosts++;			}			existingPosts++;  //prevents duplicating the second to last post on update		}	}}

Link to comment
Share on other sites

It this possibly because we're overriding the mime type now and IE's not registering responseText as a result?
Right, the response should be an XML object in responseXML, not a piece of text in responseText. Having you alert that was just confirming that the response was in fact going to responseText, that's all the alert was for. If the alert box is now empty, then that means the response isn't in responseText any more. If the alert box doesn't show at all, that probably means there is an error on the previous line that stops the script. You should be checking for error messages if you haven't been. You can press F12 in IE to open the developer tools, and there is a Console tab which will display all of the error messages. You can also turn on the debugger to have it stop when it encounters an error so that you can inspect all of the local variables (like xhrSubmitPost) and the function stack that has been executed. I'm assuming you're using a recent version of IE.
Link to comment
Share on other sites

Right, the response should be an XML object in responseXML, not a piece of text in responseText. Having you alert that was just confirming that the response was in fact going to responseText, that's all the alert was for. If the alert box is now empty, then that means the response isn't in responseText any more. If the alert box doesn't show at all, that probably means there is an error on the previous line that stops the script. You should be checking for error messages if you haven't been. You can press F12 in IE to open the developer tools, and there is a Console tab which will display all of the error messages. You can also turn on the debugger to have it stop when it encounters an error so that you can inspect all of the local variables (like xhrSubmitPost) and the function stack that has been executed. I'm assuming you're using a recent version of IE.
I do have IE9 installed, and I have been using the console. Unfortunately, it hasn't been throwing me any errors. The page did throw a single error when the alert stopped showing up: SCRIPT438: Object doesn't support property or method 'overrideMimeType'. I've commented out the overrideMimeType line for now and the alert is popping up again. I don't know what else to look for, though. The script isn't generating errors - at least none that the console is showing. What should my next step be?
Link to comment
Share on other sites

Why would this be failing in IE when everything seems to be going through just fine?
I guess the obvious answer is "because it's IE". I really don't see any problems though, it looks to me like IE should be getting an XML response and putting it in the responseXML property.
Link to comment
Share on other sites

Usually those headers do the trick. The only other thing that comes to mind is that IE might think the XML is malformed in some way.
It's the last part that made me wonder if I'm doing something wrong in the PHP and .txt data file. Take a look at the scripts below. Is there something that I'm missing here?XML tags contained in .txt file, these are updated by the following php when a user posts. This is more or less a tag database.
<name>Chrome Test</name><message>Chrome</message><name>Firefox Test</name><message>Firefox</message><name>Opera Test</name><message>Opera</message><name>Safari Test</name><message>Safari</message><name>IE Test</name><message>IE</message><name>lo</name><message>lorem ipsam</message>

This is the PHP that updates posts.txt and returns the updated XML. This script is also called when the page loads to fill in the existing posts.

<?php	$filename = 'posts.txt';	if ($_GET['name']) {		$handle = fopen($filename,'a');				$name = htmlentities($_GET['name']);		$message = htmlentities($_GET['message']);				$content = "\n<name>".$name."</name>\n\n<message>".$message."</message>\n";		fwrite($handle, $content);		fclose($handle);   	}		header("Content-type: text/xml");	echo '<?xml version="1.0" encoding="UTF-8"?>';	echo "\n<posts  xml:lang=\"EN\">\n";	readfile ($filename);	echo "\n\n</posts>\n";?>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...