Please help me get my AJAX demo to work.
Here's the front end code:
<html>
<head>
<title>Using Ajax and XML With Post</title>
<script language = "javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getSandwiches1()
{
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST", "sandwiches3.php",
true);
XMLHttpRequestObject.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
var xmlDocument = XMLHttpRequestObject.responseXML;
var sandwiches
= xmlDocument.getElementsByTagName("sandwich");
listSandwiches(sandwiches);
}
}
XMLHttpRequestObject.send("type=1");
}
}
function getSandwiches2()
{
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST", "sandwiches3.php",
true);
XMLHttpRequestObject.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
var xmlDocument = XMLHttpRequestObject.responseXML;
var sandwiches
= xmlDocument.getElementsByTagName("sandwich");
listSandwiches(sandwiches);
}
}
XMLHttpRequestObject.send("type=2");
}
}
function listSandwiches (sandwiches)
{
var loopIndex;
var selectControl = document.getElementById('sandwichList');
for (loopIndex = 0; loopIndex < sandwiches.length; loopIndex )
{
selectControl.options[loopIndex] = new
Option(sandwiches[loopIndex].firstChild.data);
}
}
</script>
</head>
<body>
<h1>Using Ajax and XML With Post</h1>
<form>
<input type = "button" value = "Get sandwiches"
onclick = "getSandwiches1()">
<input type = "button" value = "Get vegetarian sandwiches"
onclick = "getSandwiches2()">
<select size="1" id="sandwichList">
<option>Select a sandwich</option>
</select>
</form>
</body>
</html>
Here's the back end PHP code:
<?
header("Content-type: text/xml");
if ($_POST["type"] == "1")
$sandwiches = array('ham', 'turkey', 'cheese');
if ($_POST["type"] == "2")
$sandwiches = array('cheese', 'avocado', 'spinach');
echo '<?xml version="1.0"?>';
echo '<sandwiches>';
foreach ($sandwiches as $value)
{
echo '<sandwich>';
echo $value;
echo '</sandwich>';
}
echo '</sandwiches>';
?>
The dropdown box isn't populating with sandwiches like it's supposed to. Neither buttons do anything.
CodePudding user response:
On the back end code, when you use <?php instead of <? it works for me...