ciao,
non so come funziona il vostro script ma vi posso consigliare uno che sicuramente funziona e facile da capire e potete modificare per le vostre esigenze come ho fatto io
una cosa importante nel label for,select id e select name devono essere uguali al nome delle tabelle usate
ora vi posto il codice(ajax)
index.html
Codice PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Esempio liste di selezione in cascata</title>
<script type="text/javascript" src="lists.js"></script>
<style type="text/css">
body {
font-family: verdana, sans-serif;
font-size: 9pt;
}
select {
width: 200px;
margin: 5px 0;
}
fieldset {
border: 1px solid #d0d0d0;
padding: 5px;
width: 220px;
}
</style>
</head>
<body>
<form action="index.html" method="post">
<fieldset>
<label for="regioni">Regioni</label>
<select name="regioni" id="regioni" onChange="loadList('province', getSelected(this))" >
</select>
<label for="province">Province</label>
<select name="province" id="province">
</select>
<input type="submit" name="submit" value="Invia" />
</fieldset>
</form>
<script type="text/javascript">
//<![CDATA[
loadList('regioni', 0);
//]]>
</script>
</body>
</html>
request.php
Codice PHP:
<?php
require 'dbconfig.php';
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die;
mysql_select_db(DB_NAME) or die;
//I valori in input vanno verificati
//id deve essere un valore numerico
$pid = (int)$_REQUEST['id'];
//maschera eventuali caratteri speciali in table
$tb = mysql_real_escape_string($_REQUEST['table'], $conn);
switch($tb) {
case 'regioni':
$sql="SELECT id, nome FROM `$tb` ORDER BY nome";
break;
case 'province':
$sql="SELECT id, nome FROM `$tb` WHERE id_regione=$pid ORDER BY nome";
break;
}
//Il primo elemento della risposta è il nome della tabella (= attributo ID del tag select)
$out="$tb;";
if($result = mysql_query($sql, $conn)) {
while ($row = mysql_fetch_row($result)) {
$out .= $row[0] . '|' . $row[1] . ';';
}
}
//Rimuove il carattere ; in coda
echo rtrim($out, ';');
?>
list.js
Codice PHP:
var xmlHttp = getXmlHttpObject();
function loadList(tb, id){
xmlHttp.open('GET', 'request.php?table='+tb+'&id='+id, true);
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.send(null);
}
function addOption(select, value, text) {
//Aggiunge un elemento <option> ad una lista <select>
var option = document.createElement("option");
option.value = value,
option.text = text;
try {
select.add(option, null);
} catch(e) {
//Per Internet Explorer
select.add(option);
}
}
function getSelected(select) {
//Ritorna il valore dell'elemento <option> selezionato in una lista
return select.options[select.selectedIndex].value;
}
function stateChanged() {
if(xmlHttp.readyState == 4) {
//Stato OK
if (xmlHttp.status == 200) {
var resp = xmlHttp.responseText;
if(resp) {
//Le coppie di valori nella striga di risposta sono separate da ;
var values = resp.split(';');
//Il primo elemento è l'ID della lista.
var listId = values.shift();
var select = document.getElementById(listId);
//Elimina i valori precedenti
while (select.options.length) {
select.remove(0);
}
if(listId == 'regioni') {
addOption (select, 0, '-- Selezionare regione --');
}
var limit = values.length;
for(i=0; i < limit; i++) {
var pair = values[i].split('|');
//aggiunge un elemento <option>
addOption(select, pair[0], pair[1]);
}
}
} else {
alert(xmlHttp.responseText);
}
}
}
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;
}
dbconfig.php
Codice PHP:
<?php
//Modify constants with data needed to access your own database
define('DB_HOST','localhost');
define('DB_NAME','testdb');
define('DB_USER','testuser');
define('DB_PASSWORD','test');
?>
in fine il file sql
db.sql
Codice PHP:
CREATE TABLE `regioni` (
`id` int(11) NOT NULL auto_increment,
`nome` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
);
--
-- Dump dei dati per la tabella `regioni`
--
INSERT INTO `regioni` (`id`, `nome`) VALUES
(1, 'Lombardia'),
(2, 'Liguria'),
(3, 'Toscana'),
(4, 'Campania');
CREATE TABLE `province` (
`id` int(11) NOT NULL auto_increment,
`id_regione` int(11) NOT NULL,
`nome` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
);
--
-- Dump dei dati per la tabella `province`
--
INSERT INTO `province` (`id`, `id_regione`, `nome`) VALUES
(1, 1, 'Milano'),
(2, 1, 'Bergamo'),
(3, 2, 'Genova'),
(4, 2, 'Savona'),
(5, 3, 'Firenze'),
(6, 3, 'Lucca'),
(7, 4, 'Napoli'),
(8, 4, 'Avellino'),
(9, 4, 'Salerno');