I just started learning AJAX and have made a simple script. Below is the script.
<!doctype html>
<html>
<head>
<title>Welcome to the forum</title>
<script>
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest)
{
XMLHttpRequestObject = new XMLHttpRequest();
XMLHttpRequestObject.overrideMimeType("text/xml");
}
else
{
document.getElementById("text").innerHTML = "Sorry, your browser does not support AJAX!";
}
function getData(dataSource)
{
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
responseData = XMLHttpRequestObject.responseXML;
responseDataList = responseData.getElementsByTagName("os");
}
}
XMLHttpRequestObject.send(null);
}
function displayMenuItems(dataSource,selectID)
{
getData(dataSource);
var i;
for(i=0; i<responseDataList.length; i++)
{
document.getElementById(selectID).options[i] = new Option(responseDataList[i].firstChild.data);
}
}
</script>
</head>
<body>
<form>
<select size="1" id="os">
<option>Select and OS</option>
</select>
<input type="button" value="Display OS list" onclick="displayMenuItems('os.xml','os')" />
</form>
<div id="text">The Operating System you use will appear here!</div>
</body>
When I click the button, what I expect is to show the list of OSes in the HTML list , but it occurs only after clicking the button twice. I can’t figure out what the problem is! 🙁
Below is the XML script:
<?xml version="1.0"?>
<osList>
<os>Ubuntu</os>
<os>Fedora</os>
<os>Windows</os>
</osList>
The problem is a timing issue. The function displayMenuItems calls getData and then right away tries to iterate over responseDataList, but this list isn’t fetched yet. AJAX doesn’t block, so getData doesn’t wait for the server to respond, and returns before the responseDataList is initialized. You’ll need to call the loop in displayMenuItems after the data is fetched. You can do this by moving it into another function and calling it from the onreadystatechange callback function.