XMLHttpRequest problem

Codes here !

Moderators: egami, macek, gesf

Post Reply
paul1960

Mon Jul 30, 2012 6:26 am

I'm trying to make a WineShop e-commerce site to refresh myself on HTML and CSS and to practice Javascript. Unfortunately I found that Javascript isn't good for accessing a database on the server, I needed PHP, or ASP for that. So I went through a PHP tutorial and I think I learned how to access the DB (haven't been able to test it yet), but then I found I needed AJAX to call the PHP page. I did some research and I think I learned how to do that in AJAX but I'm never getting a complete indication from my XMLHttpRequest.readyState property. Anyone know why I never get a complete status from the request? I put in a an alert and the onreadystatechange event gets a readyState of 1 but never changes again apparently. My html and php files are in the same directory. My code is below.

HTML

Code: Select all

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
		<title>Main Page</title>
		<link rel="stylesheet" type="text/css" href="style/mainstyle.css" />
		<script type="text/javascript">
			// Record Set Variable
			var recSet;
			function populateGrape() {
				// Grape Select Input element
				var glist = document.getElementById("grape");
				// Category Select Input element
				var clist = document.getElementById("category");			
				// If Category Selection is valid
				if(clist.selectedIndex > 0) {
					// Get XMLHttpRequest Object
					var ajax = getRequest(); 
					// Prepare GET action to getGrapes.php synchronously
					ajax.open("GET", "getGrapes.php?catID="+clist.selectedIndex, false);
					// Attach onreadystatechange Event Handler
					xmlHttp.onreadystatechange = loadRecordSet; 
					// Send Request
					ajax.send(null);	
				}
				alert(recSet.toString());
				// Enable Grape Select Input
				glist.removeAttribute("disabled");	
			}

			function populateTable() {

			}
			
			function getRequest() { 
			    var req = false; 
			    try{ 
			        // most browsers 
			        req = new XMLHttpRequest(); 
			    } catch (e){ 
			        // IE 
			        try{ 
			            req = new ActiveXObject("Msxml2.XMLHTTP"); 
			        } catch (e) { 
			            // try an older version 
			            try{ 
			                req = new ActiveXObject("Microsoft.XMLHTTP"); 
			            } catch (e){ 
			                return false; 
			            } 
			        } 
			    } 
			    return req; 
			}

			loadRecordSet() {
				// if completed
				if(ajax.readyState == 4) {
					// If request successful put response in the Record set variable
					if (ajax.status == 200 || ajax.status == 304) 
						recSet = ajax.response;
					alert("got here");
				}
			}

		</script>
	</head>
    <body>
    	<hr/>
		<h1>Main Menu</h1>
		<p>Broad Selection</p>
		<div>
			<select id='category' onchange="populateGrape()">
				<option value="none"></option>
				<option value="red">Red Wines</option>
				<option value="white">White Wines</option>
			</select>
		</div>
		<p>Grape Selection (you must first select a broad category)</p>
		<div>
			<select disabled="disabled" id='grape' onchange="populateTable()">
				<option value="none">Select Category</option>
			</select>
		</div>

    </body>
</html>
PHP

Code: Select all

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=Cp1252">
	<title>Grapes Table Access</title>
	</head>
    <body onload="getGrapes()">
    <?php
		function getGrapes() {
			//Server Name Variable
			$serverName = 'PAUL-PC\SQLEXPRESS'; 
			// Connection Options
			$connOptions = array('Database'=>'WineShopDB'); 
			//Connect to DB  
			$conn = sqlsrv_connect($serverName, $connOptions) or die( print_r( sqlsrv_errors(), true));
			//Query String
			$sql = "Select GrapeName From WineShopDB.Grapes Where CategoryID =" + $_Get("catID");
			// Execute the query (the recordset $rs contains the result)
			$params = null;
			$rs = sqlsrv_query($conn, $strSQL, $params) or die( print_r( sqlsrv_errors(), true));
			//Close the Connection
			sqlsrv_close($conn);
			//Return Recordset
			return $rs;
		}
	?>
    </body>
</html>

User avatar
Nullsig
php-forum Fan User
php-forum Fan User
Posts: 979
Joined: Thu Feb 17, 2011 6:52 am
Location: Racine, WI

Mon Jul 30, 2012 7:53 am

Try prioritizing the IE ahead of other browsers.

paul1960

Mon Jul 30, 2012 11:21 am

Do you mean in the getRequest function? I tried that moved it to the first option but no luck. I'm using Eclipse and I'm not really too sure what browser it would bring up by default. I just run my app in the Preview Server.

johnj
php-forum Super User
php-forum Super User
Posts: 1803
Joined: Thu Mar 10, 2011 5:07 pm

Wed Aug 01, 2012 8:48 pm

you need to display the value for ajax.readyState in loadRecordSet and see what value it displays. If it is not 4 then it is in one of the previous states which should help you debug further.

paul1960

Thu Aug 02, 2012 6:24 am

Hi John, I put an alert in the loadRecordSet function, the readyState goes to 1 then apparently the event never fires again.

johnj
php-forum Super User
php-forum Super User
Posts: 1803
Joined: Thu Mar 10, 2011 5:07 pm

Thu Aug 02, 2012 7:03 am

you are getting the request and storing it in the variable called ajax.
var ajax = getRequest();

Then, you are using the same variable to call open(), ajax.open()

But in the next call to loadRecordSet..... what is the variable ajax inside that function called loadRecordSet????.. are you passing it??...i think that is the error.

It is better if you stop writing so many functions and write everything as one function, make it work and then try to split it into different functions of your choice.

paul1960

Fri Aug 03, 2012 7:10 am

Hey John, I haven't been able to try that, I made the ajax variable global which should have resolved that but my onchange event stopped firing and I couldn't figure out why till I read a post on a jquery forum about events not firing if they used ajax to call another page unless they were in a special div data role tag which looks as if it is not supported in xhtml. I was able to get my event to fire again by commenting out everything that had to do with the XMLHttpRequest, but it was firing before so I must have changed something to make it stop. Its times like these I wish I had used some kind of source control I could role it back with. I'll keep plugging away at it and if you have any idea why the event stopped firing I'd love to hear it.

paul1960

Fri Aug 03, 2012 9:11 am

I changed my handler like this and its working again actually better than it was before but still not successfully I'm a little confused by the order in which I'm getting my alerts they go off in this order

event fired
got here
got req
got event
readyState = 1
got open
readyState = 1
readyState = 2
readyState = 3
readyState = 4
DB Acess unsuccessful ajax status 404
got sent

I wasn't expecting all those readyState changes before the send method was called. I guess the alerts just happened faster in the event than the alert that came after the send so the 4 status changes are probably in reponse to the send method call. Probably the first readyState = 1 was in response to the open method call, just faster than the alert that followed it. The 404 status indicates the url wasn't found, its in the same directory as the javascript file so I'm not sure why I'm getting that.

Code: Select all

function populateGrape() {
	alert("event fired");
	// Record Set Variable
	var recSet = null;
	// Grape Select Input element
	var glist = document.getElementById("grape");
	// Category Select Input element
	var clist = document.getElementById("category");
	// Request Variable
	var ajax = false;
	// If Category Selection is valid
	if(clist.selectedIndex > 0) {
		// Get XMLHttpRequest Object
		alert("got here");
		ajax = getRequest();
		if(!ajax)
			alert("Get Request Failed");
		else
			alert("got req");
		// Attach onreadystatechange Event Handler
		ajax.onreadystatechange=function(){
			alert(ajax.readyState);
			if(ajax.readyState == 4)
				//If request successful put response in the Record set variable
				if (ajax.status == 200) 
					recSet = ajax.response;
				else
					alert("DB Acess unsuccessful ajax status " + ajax.status);

		};
		alert("got event");
		// Prepare GET action to getGrapes.php synchronously
		ajax.open("GET", "getGrapes.php?catID="+clist.selectedIndex, true);
		alert("got open");
		// Send Request
		ajax.send(null);
		alert("got sent");
	}
}

function getRequest() { 
    var req = false;
 	//IE
    try{ 
    	req = new ActiveXObject("Msxml2.XMLHTTP"); 
    } catch (e){ 
        try{ 
        	//most browsers 
	        req = new XMLHttpRequest();
        } catch (e) { 
            //try an older version 
            try{ 
                req = new ActiveXObject("Microsoft.XMLHTTP"); 
            } catch (e){ 
                return false; 
            } 
        } 
    } 
    return req; 
}

johnj
php-forum Super User
php-forum Super User
Posts: 1803
Joined: Thu Mar 10, 2011 5:07 pm

Fri Aug 03, 2012 7:32 pm

First, make sure the control is reaching your php file. If it is not, then there is an error in the way you are calling your php file.

Post Reply