I am in need of converting a javascript function that currently uses XMLHttpRequest() to perform a synchronous data fetch from the server into an asynchronous one. The function currently caches the data received to avoid multiple fetches. However, when attempting to switch to asynchronous fetching, the data is not returned in time for the callers to retrieve it. This has led to consideration of ways around the issue, such as firing functions in an onload list after the load is completed. While the synchronous method currently works fine, it is deprecated and not recommended. This has prompted the search for alternative mechanisms. One idea is to modify the XMLHttpRequest() function to track calls from other functions and handle the necessary actions once the data is received. This could involve breaking calling functions into two parts - one for requesting the data and another for handling actions post-data retrieval. Despite the potential solution, the process seems cumbersome and there may be a better way yet to be discovered. The current code snippet demonstrates the synchronous method:
var xmlhttp;
var dn = window.location.hostname;
var srcURL = "http://"+dn+"/unpublished/latest/this.txt";
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", srcURL, false);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.send("fname=Who&lname=Cares");
if (xmlhttp.readyState == 4 && xmlhttp.status==200)
{
var siteData = xmlhttp.responseText;
. . .
The asynchronous version, which works in fetching the data but poses timing issues for some callers, bears resemblance to the synchronous method. Here is a snippet of the asynchronous code:
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//callback function for the AJAX request
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status==200)
{
var siteData = xmlhttp.responseText;
... etc ...
Lastly, an example of the callers to the function getSiteData()
is shown below:
<script type = "text/javascript">
function setLinkToContact(objId)
{
document.getElementById(objId).setAttribute('href',
getSiteData('contact'));
}
</script>
There are numerous callers for the "getSiteData()"
function.