A Site Description Grabber using AHAH
Didn't find what you want? Try our search
Elsewhere on this site is a description of AHAH, a simplified version of Ajax used primarily for updating (X)HTML elements in a browser-displayed page, without the hassles of parsing and transforming returned XML.
Here we present a simple project to use AHAH to grab the contents of a remote website's 'description' metatag, and display it on the page. Try it by entering a domain name (e.g. www.cnn.com) into the URL field and clicking on Fetch:
First, let's look at the code from this page:
You'll note firstly that we've called an external script file called ahahLib.js, which you can download here if you wish. This contains the code described in AHAH - Ajax Lite? elsewhere on this site:
function callAHAH(url, pageElement, callMessage, errorMessage) {
document.getElementById(pageElement).innerHTML = callMessage;
try {
req = new XMLHttpRequest();
/* e.g. Firefox */
} catch(e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
/* some versions IE */
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
/* some versions IE */
} catch (E) {
req = false;
}
}
}
req.onreadystatechange
= function() {responseAHAH(pageElement, errorMessage);};
req.open("GET",url,true);
req.send(null);
}
function responseAHAH(pageElement, errorMessage) {
if(req.readyState == 4) {
if(req.status == 200) {
output = req.responseText;
document.getElementById(pageElement).innerHTML
= output;
} else {
document.getElementById(pageElement).innerHTML
= errorMessage+"\n"+responseText;
}
}
}
Firstly, we enter a URL such as www.bbc.co.uk into the URL field, then click on 'Fetch'. The value in the URL field is passed to the callAHAH function as a parameter called url which is appended to the address of our server script, here getmeta.php. Let's look at the PHP code for that script:
$tags = @get_meta_tags('http://'.$url);
$result = $tags['description'];
if(strlen($result) > 0) {
echo $result;
} else {
echo "No description metatag was available";
}
If the call was successful, the returned text (contained in the PHP variable $result in the above script) becomes the value of the responseText property of our XMLHTTPRequest call. The function responseAHAH processes that text, applying it to our chosen HTML element, here the table cell with id = show
Before using any software from this site, please see the Terms
|