I've have been playing around with AJAX this past week... I had a client who needed a script that includes the contents of a PHP file using AJAX... I'm far from an AJAX expert but all I know is that this script works. Hopefully all the coding is correct
The main file:
Code:
<html>
<head>
<script language="javascript" type="text/javascript">
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq(page) {
http.open('get', 'load.php?page='+page);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('content').innerHTML = response;
}
}
</script>
</head>
<body>
<p><a href="javascript:sndReq('page1')">Load Page 1</a> : <a href="javascript:sndReq('page2')">Load Page 2</a> : <a href="javascript:sndReq('page3')">Load Page 3</a></p>
<div id="content">
This is the default content.
</div>
</body>
</html>
Basically when you click one of the
javascript:sndReq('pagename'), it will load whatever you put inside the inverted commas onto the page. So in this case it would load
pagename.php. All loaded text is placed into the
content div.
In the
sndReq() function, it opens
load.php which checks that the page exists. If the page does exist, it will load the page. If not, it will give an error message.
The load.php file:
PHP Code:
<?php
if ($_GET['page'] && file_exists($_GET['page'].".php")) {
include($_GET['page'].".php");
} else {
echo "This page does not exist!";
?>
The PHP file is very basic. It checks that the file exists and then includes it.
Now all you have to do is create the .php files.
Hope that helps
