Good XmlHttpRequest example

http://www.xml.com/pub/a/2005/02/09/xml-http-request.html

I’m working through the example and have converted the php server code to ASP.NET/C#. I’m getting a Javascript error though and believe it has something to do with how I’m returning the XML to the Response stream. Can anyone help me diagnose this thing?

default.aspx (form with js code)


     <%@ Page language="c#" Codebehind="default.aspx.cs" AutoEventWireup="false" Inherits="XmlHttpRequest._default" %>
     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 
     
     <html>
     	<head>
     		<title>XmlHttpRequest Example</title>
     		
     		<style type="text/css">
     		
     			span.hidden
     			{
     				display: none;
     			}
     			
     			span.error
     			{
     				display: inline;
     				color: black;
     				background-color: pink;
     			}
     		</style>
     		
     		<script type="text/javascript">
     		
     			var req;
     			
     			function loadXMLDoc(url)
     			{
     				if (window.XMLHttpRequest)
     				{
 		 		// branch for native XMLHttpRequest object
 					req = new XMLHttpRequest();
 		 		req.onreadystatechange = processReqChange;
 					req.open("GET", url, true);
 					req.send(null);
     				}
  				else if (window.ActiveXObject)
     				{
 		 		// branch for IE/Windows ActiveX version
 		 		req = new ActiveXObject("Microsoft.XMLHTTP");
     					
 					if (req)
     					{
 		 		 req.onreadystatechange = processReqChange;
    				  req.open("GET", url, true);
 						req.send();
     					}
     				}
     			}
     			
     			function processReqChange()
     			{
 				// only if req shows "complete"
     				if (req.readyState == 4)
     				{
 					// only if "OK"
 					if (req.status == 200)
     					{
 		 			response = req.responseXML.documentElement;
 		 			method = response.getElementsByTagName('method')[0].firstChild.data;
 		 			result = response.getElementsByTagName('result')[0].firstChild.data;
 		 			eval(method + '(\\'\\', result)');
     					}
     					else
     					{
 		 			alert("There was a problem retrieving the XML data:\
" + req.statusText);
     					}
     				}
     			}
 		 		 			 	
     			 function checkName(input, response)
     			 {
     				 if (response != '')
     				 {
 					 // Response mode
 			 		message = document.getElementById('nameCheckFailed');
     					 
 					 if (response == 'true')
 			 		 message.className = 'error';
 					 else
 			 		 message.className = 'hidden';
     				 }
     				 else
     				 {
 					 // Input mode
 			 		url = 'http://localhost/XmlHttpRequest/checkUserName.aspx?q=' + input;
 					 loadXMLDoc(url);
     				 }
     			 }
     				 
     		</script>
     
     	</head>
     	
     	<body>
     
 		<input id="username" name="username" type="text" onblur="checkName(this.value,'')" />
     		  
     		<span class="hidden" id="nameCheckFailed">
     		  This name is in use, please try another. 
     		</span>
     	
     	</body>
     
     </html>
     

checkUserName.aspx.cs (logic)


     namespace XmlHttpRequest
     {
     	public class checkUserName : System.Web.UI.Page
     	{
     		private void Page_Load(object sender, System.EventArgs e)
     		{
     			TextWriter tw = Response.Output;
     			tw.Write( NameInUse(Request["q"]) );
     			tw.Flush();
     			tw.Close();
     		}
     
     		private string NameInUse(string q)
     		{
     			bool isInUse = true;
     
     			// should query database
     			if( q != null )
     			{
     				switch(q)
     				{
 					case "fred":
 		 			isInUse = true;
 						break;
 					case "joe":
 		 			isInUse = true;
 						break;
 					default:
 		 			isInUse = false;
 						break;
     				}
     			}
     			else
     			{
     				isInUse = false;
     			}
     
     			// create response xml
 			string res = "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\" standalone=\\"yes\\"?>\
" +
     				"<response>\
" +
 				"\	<method>checkName</method>\
" +
 				"\	<result>" + isInUse + "</result>\
" +
     				"</response>";
     
     			System.Diagnostics.Debug.WriteLine("res: " + res);
     
     			return res;
     		}
     	}
     }
     

My error is coming from this js function:
It keeps saying the response object is null on the bolded line.


   function processReqChange()
   {
   	// only if req shows "complete"
   	if (req.readyState == 4)
   	{
   		// only if "OK"
   		if (req.status == 200)
   		{
   		response = req.responseXML.documentElement;
   		[i][u][b]method = response.getElementsByTagName('method')[0].firstChild.data;[/b][/u][/i]
   		result = response.getElementsByTagName('result')[0].firstChild.data;
   		eval(method + '(\\'\\', result)');
   		}
   		else
   		{
   		alert("There was a problem retrieving the XML data:\
" + req.statusText);
   		}
   	}
   }
   

I got it all converted over to .NET and working.

default.aspx


  <%@ Page language="c#" Codebehind="default.aspx.cs" AutoEventWireup="false" Inherits="XmlHttpRequest._default" %>
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 
  
  <html>
  	<head>
  		<title>XmlHttpRequest Example</title>
  		
  		<style type="text/css">
  		
  			span.hidden
  			{
  				display: none;
  			}
  			
  			span.error
  			{
  				display: inline;
  				color: black;
  				background-color: pink;
  			}
  			
  		</style>
  		
  		<script type="text/javascript">
  		
  			var req;
  			
  			function loadXMLDoc(url)
  			{
  				if (window.XMLHttpRequest)
  				{
 		 		// branch for native XMLHttpRequest object
 					req = new XMLHttpRequest();
 		 		req.onreadystatechange = processReqChange;
 					req.open("GET", url, true);
 					req.send(null);
  				}
  				else if (window.ActiveXObject)
  				{
 		 		// branch for IE/Windows ActiveX version
 		 		req = new ActiveXObject("Microsoft.XMLHTTP");
  					
 					if (req)
  					{
 		 		 req.onreadystatechange = processReqChange;
 		 		 req.open("GET", url, true);
 						req.send();
  					}
  				}
  			}
  			
  			function processReqChange()
  			{
  				// only if req shows "complete"
  				if (req.readyState == 4)
  				{
 					// only if "OK"
 					if (req.status == 200)
  					{
 		 			response = req.responseXML.documentElement;
 		 			method = response.getElementsByTagName('method')[0].firstChild.data;
 		 			result = response.getElementsByTagName('result')[0].firstChild.data;
 		 			eval(method + '(\\'\\', result)');
  					}
  					else
  					{
 		 			alert("There was a problem retrieving the XML data:\
" + req.statusText);
  					}
  				}
  			}
 		 		 			 	
  			 function checkName(input, response)
  			 {
  				 if (response != '')
  				 {
 					 // Response mode
 			 		message = document.getElementById('nameCheckFailed');
  					 
 					 if (response == 'True')
 			 		 message.className = 'error';
  					 else
 			 		 message.className = 'hidden';
  				 }
  				 else
  				 {
 					 // Input mode
 			 		url = 'http://localhost/XmlHttpRequest/checkUserName.aspx?q=' + input;
 					 loadXMLDoc(url);
  				 }
  			 }
  				 
  		</script>
  
  	</head>
  	
  	<body>
  
 		<input id="username" name="username" type="text" onblur="checkName(this.value,'')" />
  		  
  		<span class="hidden" id="nameCheckFailed">
  		  This name is in use, please try another. 
  		</span>
  	
  	</body>
  
  </html>
  

checkUserName.aspx.cs


  using System;
  using System.Collections;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Web;
  using System.Web.SessionState;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.HtmlControls;
  using System.IO;
  
  namespace XmlHttpRequest
  {
  	public class checkUserName : System.Web.UI.Page
  	{
  		private void Page_Load(object sender, System.EventArgs e)
  		{
  			Response.ContentType = "text/xml";
  			Response.Write( this.NameInUse(Request["q"]) );
  			Response.End();
  		}
  
  		private string NameInUse(string q)
  		{
  			bool isInUse = true;
  
  			// should query database
  			if( q != null )
  			{
  				switch(q)
  				{
 					case "fred":
 		 			isInUse = true;
 						break;
 					case "joe":
 		 			isInUse = true;
 						break;
 					default:
 		 			isInUse = false;
 						break;
  				}
  			}
  			else
  			{
  				isInUse = false;
  			}
  
  			// create response xml
 			string res = "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\" standalone=\\"yes\\"?>" +
  				"<response>" +
 				"<method>checkName</method>" +
 				"<result>" + isInUse + "</result>" +
  				"</response>";
  
  			System.Diagnostics.Debug.WriteLine("res: " + res);
  
  			return res;
  		}
  	}
  }
  

Just as an FYI, I just went through same problem, I had a struts action which was writing to the PrintWriter and all was well, I then switched over to a velocity template (to do the right thing) and was getting the null response object.

Turns out that my velocity template just needed an extra newline at the end. Seems that the req.responseXML.documentElement needs a newline at very end. What was maddening was that the req.responseText looked fine!

dan