Posts Tagged ‘PHP javascript Ajax’

PHP and static Ajax – no more frames

Saturday, June 21st, 2008

So I’m playing with PHP (it’s not so bad, but I’m not convinved its performance is up to the uses I’m seeing it put to), and I’ve thought of a cool way to do simple content management with Ajax and static pages. I don’t know if this is a common technique, but I think it would be useful in some situations. I created a top level page with a div area that I want to paste content into, and use PHP to scan a directory looking for subdirectories that start with a specific pattern (in this case “r_”), and create a menu item for each one found. For each of these I create a link to a javascript method to load a file called index.php from that directory. It’s kind of like using frames, but a lot cleaner. I never really liked frames anyway. And it’s really easy to add new items – I just add a new subdirectory containing an index.php with the content of the second div. I can also add links to other directories get loaded teh same way but that don’t get displayed in the menu. The code follows:

I’ve build a simple page with two div areas, the first contains the PHP code to scan the directory, the second will be used to display the dynamic content:


<body>
<div id="menu">
//root path containing CMS items as sub-directories
$path = ".";
//open the directory
$dir_handle = @opendir($path) or die("Unable to open $path");
//loop through directory entries
while ($file = readdir($dir_handle))
{
if (strstr($file, "r_"))
{
$file=substr($file, 2, strlen($file)-1);
echo "$file
";
}
}
//close the directory
closedir($dir_handle);
</div>
<div id="content">
</div>

And the following javascript:

//synchronous javascript request handler
function sJax (url) {
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert("SJAX action failed.");
return false;
}
http_request.open('GET', url, false);
http_request.send(null);
if(http_request.status == 200) {
return http_request;
} else {
return null;
}
}
function load(url)
{
document.getElementById("content").innerHTML = sJax(url).responseText;
}
function loadlink(link)
{
var url = link + '/index.php';
load(url);
}
function loadDir(path)
{
var url = 'r_' + path + '/path.php';
load(url);
}