www.webdeveloper.com
Results 1 to 6 of 6

Thread: XMLHttpRequest getting undefined

  1. #1
    Join Date
    Nov 2011
    Posts
    3

    XMLHttpRequest getting undefined

    Hi all,

    I am just new to JavaScript and Ajax and am trying to load a page that I made inside of another page. The page I am trying to load is a utility such as a measurement calculator. When a radio button is pressed I would like it to load in a box that is below. However, when I click on a radio button to load the page, all I get in the box is "undefined". Any suggestions?

    Here is my code for the main page:
    Code:
    <?xml version = "1.0" encoding = "utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns = "http://www.w3.org/1999/xhtml">
    <head>
    	<title> TME1 | Tyson Elford 2750728 | COMP 466 </title>
    	<link rel = "stylesheet" type = "text/css"
    		href = "../Shared/style.css" />
    	<script type = "text/javascript">
    	<!--
    		document.writeln("<h1>Welcome to TME 1 - Project 3</h1>");
    		document.writeln("<h3>Choose below to dive into the context for this Project</h3>");
    		
    		//Ajax enabled page
    		//var to hold XMLHttpRequest
    		var asyncRequest;
    		function getContent(url){
    			//try to make an requset object
    			try{
    				asyncRequest = new XMLHttpRequest();
    				asyncRequest.onreadystatechange = stateChange;
    				asyncRequest.open("GET", url, true);
    				asyncRequest.send(null);
    			//If the request fails, send an alert message
    			}catch(exception){
    				window.alert("Async Request Failed!");
    				window.alert(exception);
    			}
    		}//END getContent
    		
    		function stateChange(){
    			//window.alert(asyncRequest.readyState + " and " +
    				//asyncRequest.status);
    			if( asyncRequest.readyState == 4 && asyncRequest.status == 0){
    				document.getElementById("contentArea").innerHTML = 
    					asyncRequest.respondText;
    			}
    		}
    		
    	</script>
    <head>
    
    <body>
    	
    	<input type = "radio" Name = "raid" value = "measure"
    		checked = "unchecked" onclick = 'getContent("measure.html")'/>Measurement Converter</br>
    	<input type = "radio" Name = "raid" value = "mortgage"
    		checked = "unchecked" onclick = 'getContent("mortgage.html")' />Mortgage Calculator</br>
    	<input type = "radio" Name = "raid" value = "raid"
    		checked = "unchecked" onclick = 'getContent("raid.html")' />RAID Calculator</br>
    	<div class = "box" id = "contentArea">&nbsp;</div>
    </body>
    and just a sample of one of the pages I would like to load inside of this page, measure.html:

    Code:
    <?xml version = "1.0" encoding = "utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns = "http://www.w3.org/1999/xhtml">
    <head>
    	<title> TME1 | Tyson Elford 2750728 | COMP 466 </title>
    	<link rel = "stylesheet" type = "text/css"
    		href = "../Shared/style.css" />
    		
    	<script type = "text/javascript">
    		<!--
    			document.writeln("<h1>Measurement Calculator</h1>");
    			
    			//Test weather a var is a number or not
    			//Return true for number false otherwise
    			function testNumber(num){
    				var test = new Boolean();
    				test = isNaN(num);
    				return (!test);
    			}
    			
    			//Function to calculate Length and Area conversions
    			function lButton(form, sq0){
    				//sq is a dummy varible to distingush between 
    				//which item to convert where weight = 0
    				//legth = 1, area = 2, volume = 3
    				var sq = sq0;
    				var cm;
    				var inch;
    				a = form.a.value;
    				b = form.b.value;
    				var calcGo = new Boolean(true);
    				//Check to make sure a number is present
    				if(a == ""  && b == ""){
    					window.alert("You must enter at least one number");
    					calcGo = false;
    					//If bad data set calcGo to false
    				}
    				//Check if two numbers are entered causing a problem
    				if(a != "" && b != ""){
    					window.alert("You must enter only one number");
    					calcGo = false;
    				}
    				//Run conversion if the above tests passed
    				if(calcGo){
    					if(a == ""){
    						//Calculate b to a
    						if(testNumber(b)){
    							var bi = parseFloat(b);
    							var ai;
    							switch (sq){
    								//Calculate which value of a is needed for
    								//a given b
    								case 0: ai = parseFloat(bi * 2.2);
    									break;
    								case 1: ai = parseFloat(bi * 2.54);
    									break;
    								case 2: ai = parseFloat(bi * 0.15500031);
    									break;
    								case 3: ai = parseFloat(bi * 0.0610237438366662);
    							}
    							form.a.value = ai;	
    						}
    						else{
    							window.alert("Please enter a number");
    						}
    					}
    					else{
    						//Cacluate a to b
    						if(testNumber(a)){
    							var ai = parseFloat(a);
    							var bi;
    							switch (sq){
    								//Calculate which value is needed for 
    								//a given a.
    								case 0: bi = parseFloat(ai / 2.2);
    									break;
    								case 1: bi = parseFloat(ai / 2.54);
    									break;
    								case 2: bi = parseFloat(ai / 0.15500031);
    									break;
    								case 3: bi = parseFloat(ai / 0.0610237438366662);
    							}
    							form.b.value = bi;
    						}
    						else{
    							window.alert("Please enter a number");
    						}
    					}
    				}
    			}//END lButton
    		// -->
    	</script>
    </head>
    <body>
    	<!-- Table for fields for weight conversion -->
    	<form action = "">
    		<table><caption><h3>Weight lbs to kg</h3></caption>
    			<tr><td> Lbs </td>
    			<td> <input id = "a" type = "text" />
    			</td></tr>
    			<tr><td> Kg </td>
    			<td> <input id = "b" type = "text" />
    			</td></tr>
    			<tr><td><input type = "button" value = "Convert Weight" 
    				onclick = "lButton(this.form, 0)" />
    			</td></tr>
    		</table>
    	</form>
    	<!-- Table for fields for length conversion -->
    	<form action = "">
    		<table><caption><h3>Length conversion</h3></caption>
    			<tr><td> Centimetre </td>
    			<td> <input id = "a" type = "text" />
    			</td></tr>
    			<tr><td> Inch </td>
    			<td> <input id = "b" type = "text" />
    			</td></tr>
    			<tr><td><input type = "button" value = "Convert Length" 
    				onclick = "lButton(this.form, 1)" />
    			</td></tr>
    		</table>
    	</form>
    	<!-- Table for fields for area conversion -->
    	<form action = "">
    		<table><caption><h3>Area conversion</h3></caption>
    			<tr><td> Squared Inch </td>
    			<td> <input id = "a" type = "text" />
    			</td></tr>
    			<tr><td> Square Centimetre </td>
    			<td> <input id = "b" type = "text" />
    			</td></tr>
    			<tr><td><input type = "button" value = "Convert Area" 
    				onclick = "lButton(this.form, 2)" />
    			</td></tr>
    		</table>
    	</form>
    	<!-- Table for fields for volume conversion -->
    	<form action = "">
    		<table><caption><h3>Volume conversion</h3></caption>
    			<tr><td> Cubed Inch </td>
    			<td> <input id = "a" type = "text" />
    			</td></tr>
    			<tr><td> Cubed Centimetre </td>
    			<td> <input id = "b" type = "text" />
    			</td></tr>
    			<tr><td><input type = "button" value = "Convert Volume" 
    				onclick = "lButton(this.form, 3)" />
    			</td></tr>
    		</table>
    	</form>
    </body>
    </html>

  2. #2
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,277
    I do not know what is wrong in your resquest (your code do not work with old versions of Internet Explorer, but there is probably others errors ?)... I take the functions made by Peter Paul Koch on this page.

    This looks like this in your page :
    HTML Code:
    <?xml version = "1.0" encoding = "utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns = "http://www.w3.org/1999/xhtml">
    <head>
    	<title> TME1 | Tyson Elford 2750728 | COMP 466 </title>
    	<link rel = "stylesheet" type = "text/css"
    		href = "../Shared/style.css" />
    	<script type = "text/javascript">
    	<!--
    		document.writeln("<h1>Welcome to TME 1 - Project 3</h1>");
    		document.writeln("<h3>Choose below to dive into the context for this Project</h3>");
    	// Ajax from PPK http://www.quirksmode.org/js/xmlhttp.html
    var xmlObj=false;
    var xmlFct=[function(){return new XMLHttpRequest()}
    	,function(){return new ActiveXObject("Msxml2.XMLHTTP")}
    	,function(){return new ActiveXObject("Msxml3.XMLHTTP")}
    	,function(){return new ActiveXObject("Microsoft.XMLHTTP")}];
    for (var i=0;i<xmlFct.length;i++) {try{xmlObj = xmlFct[i]();}catch(e){continue;}break;}
    function sndRqu(url,cllbck,pstDta){
    	var req=xmlObj;
    	if (!req) return;
    	var mth=(pstDta)? "POST":"GET";
    	req.open(mth,url,true);
    	req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    	if (pstDta) req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    	req.onreadystatechange=function(){
    		if (req.readyState!=4) return;
    		if (req.status!=200 && req.status!=304) {// 200 Ok, 304 Redirection Not modified
    //			alert('HTTP error ' + req.status);
    			return;}
    		cllbck(req);}
    	if (req.readyState==4) return;
    	req.send(pstDta);
    };
    </script>
    <head>
    <body>
    	<input type = "radio" Name = "raid" value = "measure"
    		checked = "unchecked" onclick = 'sndRqu("measure.html",function(r){alert(r.responseText)})'/>Measurement Converter</br>
    	<input type = "radio" Name = "raid" value = "mortgage"
    		checked = "unchecked" onclick = 'sndRqu("mortgage.html",function(r){alert(r.responseText)})' />Mortgage Calculator</br>
    	<input type = "radio" Name = "raid" value = "raid"
    		checked = "unchecked" onclick = 'sndRqu("raid.html",function(r){alert(r.responseText)})' />RAID Calculator</br>
    	<div class = "box" id = "contentArea">&nbsp;</div>
    </body>
    The function to use is sndRqu(url,cllbck,pstDta) with three arguments : the url (with ?key=value&... for GET requests), a call back function (which is called with the response r) and the POST data (only for POST request).

    This works (and you can see the contents of the pages with the alert statements), but you have not to load the entire pages ! You have only to load the contents of the bodies (replace the sndRqu("measure.html",function(r){alert(r.responseText)}) by a sndRqu("measure.txt",function(r){document.getElementById("contentArea").innerHTML=r.responseText}).

    An other problem is too load the scripts, (first you can perhaps load the scripts with the opening page) see, for example this page or this for further explanations...
    Last edited by 007Julien; 11-20-2011 at 02:57 PM.

  3. #3
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    And a general note:
    Code:
    <?xml version = "1.0" encoding = "utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    ...
    Never insert that (the red XML declaration) in your XHTML code. The Doctype should be the very first declaration of the document. Anything literally written above the Doctype (except from possible server-side "invisible codes") might spoil things. After all, that XML declaration is absolutely useless and a non-sense. Your document is an XHTML one, not an XML.

    If you need an encoding, use the meta-tag for that:
    Code:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    Last edited by Kor; 11-21-2011 at 10:03 AM.

  4. #4
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    Code:
    if( asyncRequest.readyState == 4 && asyncRequest.status == 0){
    200 == HTTP for OK, so you need to be checking for

    Code:
    if( asyncRequest.readyState == 4 && asyncRequest.status == 200){
    As for other errors, don't know until you iron that one out.

  5. #5
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,277
    It is in theory and has a practice more complicated
    JQuery (1.3.2.js) gave this function (lines 3682-3690)
    Code:
    	// Determines if an XMLHttpRequest was successful or not
    	httpSuccess: function( xhr ) {
    		try {
    			// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
    			return !xhr.status && location.protocol == "file:" ||
    				( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
    		} catch(e){}
    		return false;
    	}

  6. #6
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Quote Originally Posted by 007Julien View Post
    It is in theory and has a practice more complicated
    JQuery (1.3.2.js) gave this function (lines 3682-3690)
    Code:
    	// Determines if an XMLHttpRequest was successful or not
    	httpSuccess: function( xhr ) {
    		try {
    			// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
    			return !xhr.status && location.protocol == "file:" ||
    				( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
    		} catch(e){}
    		return false;
    	}
    I don't think that is related directly with the OP's issue, even it is well to be known. That is an old IE bug (reported already long time ago for IE7 and IE8 - not sure about IE9), and it comes only when a PUT request expects a 204 status (No Content Returned).

    But as long as the OP needs a response, the simple check for status 200 should be enough

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles