Page 1 of 1

PHP/AJAX: HTML displayed as text

Posted: Sat May 19, 2007 5:13 pm
by thiscatis
Hi, I'm working on a basic ajax tutorial.
You give your name and email in a field, hit submit and the data is displayed by calling a javascript function.
The php file to read the data is:

Code: Select all

<?php

$userName = $_REQUEST['userName'];
$userEmail = $_REQUEST['userEmail'];

header("Cache-Control : no-cache, must-revalidate" );
header("Expires : Mon, 26 Jul 1995 05:00:00 GMT");
header('Content-type: text/html');

echo "Your Name is: $userName";
echo "<br />";
echo "Your Email is: $userEmail";

?>
The ajax script:

Code: Select all

<script type="text/javascript" >

var xmlHttp;
	
	function createXMLHttpRequest() {
		if (window.ActiveXObject) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			
		}
		else if (window.XMLHttpRequest) {
			xmlHttp = new XMLHttpRequest();
			
		}
	}


	function createQueryString() {
	
		var userName = document.getElementById("userName") .value;
		var userEmail = document.getElementById("userEmail") .value;
		
		var queryString = "userName=" + userName + "&userEmail=" + userEmail;
		
		return queryString;
	}
	
	function doRequestUsingPOST() {
		createXMLHttpRequest();
		
		var url = "GetAndPostExample.php";
		var queryString = createQueryString();
		
		xmlHttp.open("POST", url, true);
		xmlHttp.onreadystatechange = handleStateChange;
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
		xmlHttp.send(queryString);
	}
	
	function handleStateChange() {
		if(xmlHttp.readyState == 4) {
			if(xmlHttp.status == 200) {
				parseResults();
			}
		}
	}
	
	function parseResults() {
		var responseDiv = document.getElementById("serverResponse");

			if(responseDiv.hasChildNodes()) {
				responseDiv.removeChild(responseDiv.childNodes[0]);
				
			}
			
		var responseText = document.createTextNode(xmlHttp.responseText);
			responseDiv.appendChild(responseText);
	
	}

</script>
Problem is that the html is just being displayed as text?!
I do have my headers correct, do I?

Posted: Sat May 19, 2007 5:19 pm
by bdlang
Does the page source show the HTML? Or you're expecting actual HTML tags to be output?

Posted: Sat May 19, 2007 5:22 pm
by thiscatis
it just displays the <br /> as text instead of parsing it as html as a linebreak

Re: PHP/AJAX: HTML displayed as text

Posted: Sat May 19, 2007 6:58 pm
by volka
try

Code: Select all

function parseResults() {
  responseDiv = document.getElementById("serverResponse");
  responseDiv.innerHTML = xmlHttp.responseText;
}

Posted: Sun May 20, 2007 3:43 am
by Kieran Huggins
I think the browser treats the response as text in "xmlHttp.responseText" - you need to get your nodes from "responseXML"

...however, it's not that simple :-(

In order for the browser to populate "responseXML" you need to send the response with a valid "text/xml" header, and not "text/html".

There's more on this bug at PPK's quirksmode