Presented below is a function that utilizes Ajax:
function fetchSource(callback){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 &&ajaxRequest.status==200){
var sourceData = ajaxRequest.responseText;
callback(sourceData);
}
}
ajaxRequest.open("POST", "takesource4.php", true);
ajaxRequest.send(null);
}
In addition, we have the following code snippet:
var response4;
function executeFunction() {
fetchSource(function(sourceData){
response4 = sourceData;
});
alert(response4);
}
The above function is called using the button below:
<div id="run">
<button id="button_run" class="button" onclick="executeFunction()">Run</button>
</div>
Upon clicking the button, instead of displaying the expected response from the Ajax request, it appears to be showing an undefined value (undefined
), as evident in the line below:
alert(response4);