Possible Duplicate:
How can I refresh a detail select list when my master select changes using AJAX
I'm just working learning PHP again after some time away and after looking around think I need to use JS/ajax to make this happen which I intend to learn more about after I get more comforable with PHP. I would like to learn how to do this for some thing I am working on now.
I have a table of parent items which I display as a list of links. When a parent item is clicked I want the child items of the clicked parent to be displayed in another list. I can get the 2 lists to display with simple queries I just don't know how to get the page/sql query to update when clicked.
<?php require ('connection.inc.php'); ?>
<div id="lists">
<h3>Lists</h3>
<?php
$lists = mysql_query("SELECT * FROM lists")
or die(mysql_error());
while($info = mysql_fetch_array( $lists ))
{
echo "<a href=\"#\">".$info['ListName']."</a><br />";
}
?>
</div>
<div id='listitems'>
<h3>List <?php $parent=2; echo $parent?> Items</h3>
<?php
$listitems = mysql_query("SELECT * FROM listitems WHERE parent=$parent")
or die(mysql_error());
while($info = mysql_fetch_array( $listitems ))
{
echo $info['itemName']."<br />";
}
?>
</div>
Code issues aside (mysql_* == mucho deprecato), you need to check if the request is AJAX and output listitems.
I used jquery to simplify the ajax request.
<?php
require ('connection.inc.php');
/* AJAX request */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
$query = sprintf('SELECT * FROM listitems WHERE parent=%d',
mysql_real_escape_string($_REQUEST['parent']));
$listitems = mysql_query($query)
or die(mysql_error());
printf('<h3>List %d Items</h3>', $_REQUEST['parent']);
while($info = mysql_fetch_array( $listitems ))
{
echo $info['itemName']."<br />";
}
exit;
}
/* Normal request */
?>
<div id="lists">
<h3>Lists</h3>
<?php
$lists = mysql_query("SELECT * FROM lists")
or die(mysql_error());
while($info = mysql_fetch_array( $lists ))
{
echo "<a href=\"#\">".$info['ListName']."</a><br />";
}
?>
</div>
<div id='listitems'>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
jQuery(function($)){
$('#lists').delegate('a', 'click', function(){
$('#listitems').load(window.location.pathname, {parent: $(this).text()});
return false;
});
}
</script>