I was bored so I quickly hacked up what I call “the poor man’s AJAX”. Instead of using XML calls it dynamically adds a script element, which loads data from the server. It has long been known that you can do AJAX-style calls like this, but there were no good examples anywhere.
index.html
<html>
<head>
<script language="javascript" type="text/javascript">
function doRequest(url) {
msg = "belch";
//Does URL begin with http?
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
//make new JS element
var jscript = document.createElement('script');
jscript.type = 'text/javascript';
jscript.src = url;
//add javascript element to document, thus initiating the poor-man's ajax call
//(note, you must use the DOM methods, from my experience .innerHTML will not force scripts to run)
document.body.appendChild(jscript);
}
</script>
</head>
<body>
<input type="button" onclick="doRequest('http://yoururl.tld/path/test.php');" value="Do it!"><br>
<div id="response"></div>
</body>
</html>
test.php
alert(msg);
document.getElementById('response').innerHTML = msg;
That’s all there is to it. I kind of doubt using dynamic script elements would be practical for large web applications, but for small things it should be fine.
Please subscribe, or else I will cry. Do you really want to make a programmer cry?

Leave a Reply