Hi,
This is a really simply tutorial so you can integrate your php with ajax. The example code utilizes a universal function called get. You can pass the get function the php file name to execute, the div id where the results are to be displayed, and 2 url variable values for use in your php. The names of those variables are $_GET[‘x’] and another called $_GET[‘y’]. Use null for the div id if the php results are not to be displayed. You can also set x and y to null if you don’t need them.
Create ajax.html then copy and paste this code:
<html>
<head>
<script src=“js/ajax.js”></script>
</head>
<body>
<a href=“javascript:get(‘date’,‘displayID’,null,null)”>Display Date</a>
<div id=“displayID”></div>
</body>
</html>
In this example I used a general html link to execute the javascript get function. Javascript functions can also be called from onClick, onChange, and several other methods.
Create the ajax.js file in a folder called js. Copy and paste this code.
var xmlHttp
var divId
//get menthod parameters
//file = file name without the php extension
//div = the block level div id displaying the results
//x = get x
//y = get y
function get(file,div,x,y)
{
divId = div
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert (“Your browser does not support AJAX!”);
return;
}
//define page to run
var url=file+".php";
url=url+"?sid="+Math.random();
url=url+"&x="+x+"&y="+y;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open(“GET”,url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
//test text = resulting output
text = xmlHttp.responseText
//write to div
if(divId!=null)
{
document.getElementById(divId).innerHTML = text
}
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
}
return xmlHttp;
}
Create date.php, then copy and paste this code:
<h2>File contents</h2>
<hr />
<?php
echo date(‘M d,y’);
?>
<h2>Get array results</h2>
<hr />
<pre>
<?=print_r($_GET)?>
</pre>