I'm currently conducting some experiments involving AJAX calls using pure JavaScript, without relying on JQuery. I am curious if it's possible to populate a DIV element in the following way:
<script type="text/javascript">
function call_test() {
document.getElementById("myId").innerHTML = ajax_call("example.php?id=1") ;
}
</script>
<body>
<input type="button" onClick="call_test()" value"Test">
<div id="myId">Result will be displayed here</div>
The issue lies in how to return the result from the ajax_call function. The current code is as follows, but it doesn't seem to work:
function ajax_call(remote_file)
{
var $http,
$self = arguments.callee ;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function() {
if (/4|^complete$/.test($http.readyState)) {
return http.responseText ; // This only returns undefined
}
};
$http.open('GET', remote_file , true);
$http.send(null);
}
}
Content of remote file:
<?php
echo "<h1>Just an experiment</h1>";
?>