Tuesday, October 7, 2008

Ajax and PHP without using the XmlHttpRequest Object

There is one problem with most of the current implementations of Ajax: it has one dependency, and that is the XmlHttpRequest object. Most modern browser, like Firefox, have inbuilt support for this object, but older browsers, like Internet Explorer 6, don't have native support for this object. Luckily, IE 6 does support it, but it's built in as an ActiveX control, which means your visitors get an ugly warning message about the possible danger of an ActiveX control, or in some cases it just doesn't work at all.

In this tutorial, I will show you how to use Ajax without even having to use the XmlHttpRequest object.

The basics

If we can't use the XmlHttpRequest object, we must find some other way to include content from another page, without having to resort to other objects or non-standard things. A great candidate for this would be the <script> tag, which is used to include external JavaScript files. What if, instead of using a regular JS file, we point that tag to a PHP file, which outputs JavaScript. A PHP file which looks something like this:

<?php
$html = '<b>This content came from our Ajax Engine</b>';
?>

div = document.getElementById('contentdiv');


div.innerHTML = '<?php echo $html; ?>';


When this file is used referenced in a script tag, it will try to set the innerHTML of a div with ID 'contentdiv'. But there's one problem; this file shouldn't be included when the page loads, but only when a button is clicked or some other action. To do this, we must somehow dynamically add a new script tag, which is possible using JavaScript. Something like the following would do the trick:

// Get base url

url = document.location.href;


xend = url.lastIndexOf("/") + 1;


var base_url = url.substring(0, xend);


function ajax_do (url) {


// Does URL begin with http?

if (url.substring(0, 4) != 'http') {

url = base_url + url;

}


// Create new JS element

var jsel = document.createElement('SCRIPT');

jsel.type = 'text/javascript';

jsel.src = url;

// Append JS element (therefore executing the 'AJAX' call)


document.body.appendChild (jsel);

}


This code first gets the current directory of the url, so we have a base url. The 'ajax_do' function is the thing that does all the work. It first checks whether the url passed to the function points to another domain, or is a relative file.

It then creates a new script element, using the createElement() function. After that it sets the src attribute of the script element, and adds the script element to the body, effectively 'loading' the file that is referenced by the script element.

All we need now is a simple page that triggers the Ajax call, i.e.

<html>

<head>

<title>Demo 1 - The Basic's</title>


<script type="text/javascript" src="engine.js"></script>

</head>

<body>

<div id="contentdiv">

</div>

<input type="button" onclick="ajax_do ('page1.php');" value="Get content" />


</body>

</html>

No comments: