01.20.07
Create a Simple AJAX Interfeced PHP Page
Here is a great sample of how to create an AJAX PHP page. The AJAX is a menu portion that can be expanded. It is a good "start" to a dynamic page that can be built upon.
By the end of this simple tutorial, you will have a PHP driven, AJAX Interfaced website.
In actual terms you will have an Index page which has a menu that is driven by javascript events and which will dynamically read other PHP scripts residing on your server, and will render their output within a DIV on the index page.
Create an index.php
HTML:
-
-
<script type='text/javascript' language='javascript' src='application.js'></script>
-
<link rel='stylesheet' type='text/css' href='stylesheet.css'/>
-
<title>Page Title</title>
-
</head>
-
-
-
<div id='header'>
-
Page Title
-
</div>
-
-
<div id='menu'>
-
<li onclick='menuRequest("menu1")'>Menu 1</li>
-
<li onclick='menuRequest("menu2")'>Menu 2</li>
-
</ul>
-
</div>
-
-
<div id='content'>
-
Default Content
-
</div>
-
-
</body>
-
-
</html>
Create stylesheet.css
CSS:
-
body {
-
-
}
-
-
div#header {
-
-
}
-
-
div#menu {
-
-
}
-
-
div#menu ul {
-
-
}
-
-
div#menu ul li {
-
-
}
-
-
div#content {
-
-
}
Create application.js
JavaScript:
-
function menuRequest(url)
-
{
-
var arg = url;
-
url = "content.php?q=" + url;
-
var http_request = false;
-
-
if (window.XMLHttpRequest)
-
{ // Mozilla, Safari,...
-
http_request = new XMLHttpRequest();
-
-
if (http_request.overrideMimeType)
-
{
-
http_request.overrideMimeType('text/xml');
-
// See note below about this line
-
}
-
} 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('Giving up
Cannot create an XMLHTTP instance'); -
return false;
-
}
-
-
http_request.onreadystatechange = function() { alertContents(http_request); };
-
http_request.open('GET', url, true);
-
http_request.send(null);
-
-
}
-
-
-
function alertContents(http_request)
-
{
-
if (http_request.readyState == 4)
-
{
-
if (http_request.status == 200)
-
{
-
document.getElementById("content").innerHTML=http_request.responseText;
-
}
-
else
-
{
-
alert('There was a problem with the request.');
-
}
-
}
-
}
Create content.php
PHP:
Happy Developing!
Technorati Tags: AJAX, PHP, web design, web development, AjaxKnight