Posted by Johnny on 10/06/06 19:56
here's a basic AJAX/PHP version in 3 files without the db calls, works in
both FF and IE:
// file "get_combo_data.js"
var xmlHttp
function get_cbo_data(str) {
if (str.length==0) {
document.getElementById("cbo_name").innerHTML=""
return
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request")
return
}
var url="cbo_data.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
var cbo = xmlHttp.responseText
document.getElementById("cbo_name").innerHTML="<select>"+cbo+"</select>"
}
}
function GetXmlHttpObject() {
var objXMLHttp=null
if (window.XMLHttpRequest) {
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject) {
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
// file "cbo_data.php"
<?php
# this data could come from the db
$cbo[1]="<option value=\"1\">a1</option><option
value=\"2\">a2</option><option value=\"3\">a3</option>";
$cbo[2]="<option value=\"1\">p1</option><option
value=\"2\">p2</option><option value=\"3\">p3</option>";
$cbo[3]="<option value=\"1\">o1</option><option
value=\"2\">o2</option><option value=\"3\">o3</option>";
$q=$_GET[q];
$data="";
if ($q>0 && $q<=count($cbo))
$data = $cbo[$q];
echo $data;
?>
// file "cbo.html" but would likely end being a php file so you could get
stuff from the db
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml;
charset=UTF-8"></meta>
<title>AJAX/PHP Combo box</title>
<script type="text/javascript" src="get_combo_data.js"></script>
</head>
<body>
<h1>AJAX/PHP Test Drive</h1>
<!-- you already retrieved data for this select from db -->
<select onchange="get_cbo_data(this.options[this.selectedIndex].value)">
<option value="-1" selected="selected"></option>
<option value="1">apple</option>
<option value="2">pear</option>
<option value="3">orange</option>
</select>
2nd combo appears here: <span id="cbo_name"></span>
</body>
</html>
Navigation:
[Reply to this message]
|