Heres an old ajax file i found and edited for you:
daniweb_basic_ajax_example.php
<html>
<head>
<script type='text/javascript'>
function getXMLHTTPRequest() {
var req = false;
try {
/* for Firefox */
req = new XMLHttpRequest();
} catch (err) {
try {
/* for some versions of IE */
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err) {
try {
/* for some other versions of IE */
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err) {
req = false;
}
}
}
return req;
}
function ajaxRequest(rowid){
var url = 'daniweb_ajaxData.php';
var vars = 'id='+rowid;
Req = getXMLHTTPRequest();
Req.open('POST', url, true);
Req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Req.onreadystatechange = function() {//Call a function when the state changes.
if(Req.readyState == 4 && Req.status == 200) {
document.getElementById('descriptionBox').innerHTML = Req.responseText;
//alert(Req.responseText);
}else{
document.getElementById('descriptionBox').innerHTML = 'Loading...';
}
}
Req.send(vars);
}
</script>
</head>
<body>
<?php
$data = array(
'1'=>array('heading'=>'item 1','id'=>'1','description'=>'desc 1'),
'2'=>array('heading'=>'item 2','id'=>'2','description'=>'desc 2'),
'3'=>array('heading'=>'item 3','id'=>'3','description'=>'desc 3'),
'4'=>array('heading'=>'item 4','id'=>'4','description'=>'desc 4'),
'5'=>array('heading'=>'item 5','id'=>'5','description'=>'desc 5')
);
//while($row = mysql_fetch_array($res)){
foreach($data as $row){
echo "<strong>{$row["heading"]}</strong>\r\n";
echo "<a href='javascript:' onclick='ajaxRequest({$row['id']});'>open descripton</a>\r\n";
echo "<br />\r\n";
}
?>
<div id='descriptionBox'></div>
</body>
</html>
and a second page for ajax to get the data with:
daniweb_ajaxData.php
<?php
if(ISSET($_POST['id']) && (ctype_digit($_POST['id']) || is_int($_POST['id']))){
//mysql_connect(...);
//$query = "SELECT description FROM tablename WHERE id = {$_POST['id']}";
//$result = mysql_query($query);
//$data = mysql_fetch_assoc($result);
//echo $data['description'];
$data = array(
'1'=>array('heading'=>'item 1','id'=>'1','description'=>'desc 1'),
'2'=>array('heading'=>'item 2','id'=>'2','description'=>'desc 2'),
'3'=>array('heading'=>'item 3','id'=>'3','description'=>'desc 3'),
'4'=>array('heading'=>'item 4','id'=>'4','description'=>'desc 4'),
'5'=>array('heading'=>'item 5','id'=>'5','description'=>'desc 5')
);
echo $data[$_POST['id']]['description'];
}else{
echo "ID did not pass: {$_POST['id']}";
}
?>
PHP is a server side language, php runs before the web page has loaded and generates the text to show the web browser(javascript is not running yet), so php can write and change javascript code before the page has loaded.
once the page has loaded php and its vars no longer exist, but javascript does. AJAX is javascript code that sends a request to another page for data so you can use php to get data for javascript to use without a page refresh using ajax.