I’ve been writing a lot of Ajax code to request some information from a server, and then update an element on the page with the returned HTML. The basic XMLHttpRequest code to do this is pretty simple, but I’ve specialized the code to do a couple of common things. First, it always replaces the HTML of the element with the ID given in $replacename, and it takes in a Javascript variable name so you can dynamically alter the URL parameters that are passed in. The second part is really useful when you want a client-side event to trigger the fetch, you can write <select onchange="yourajaxfunction(this.value);"> in a menu, and then define the values in each menu item. Here’s the PHP code for the function body:
function add_ajax_fetch_script($fetchurl, $parametersjsvar, $replacename)
{
?>
var xhr;
try
{
xhr = new ActiveXObject(‘Msxml2.XMLHTTP’);
}
catch (e)
{
try
{
xhr = new ActiveXObject(‘Microsoft.XMLHTTP’);
}
catch (e2)
{
try
{
xhr = new XMLHttpRequest();
}
catch (e3)
{
xhr = false;
}
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.getElementById("<?=$replacename?>").innerHTML = xhr.responseText;
else
document.getElementById("<?=$replacename?>").innerHTML = "Error code " + xhr.status;
}
};
xhr.open("GET", "<?=$fetchurl?>"+<?=$parametersjsvar?>, true);
xhr.send(null);
<?php
}
To use this code, you’d write out the signature and name of your Javascript function, call add_ajax_fetch_script() and then terminate the JS function with a closing curly brace. Eg:
function yourajaxfunction(urlsuffix)
{
<?php
add_ajax_fetch_script("http://someurl.com", "urlsuffix", "someelementid");
?>
}