Ciao a tutti,
apro questa discussione perchè ho visto che il mio problema e che ho risolto, è comune a molte persone, ovvero, popolare una select, in base alla scelte fatta su un'altra select.
La mia necessità, però, è nata dal fatto che i valori della prima e della seconda select, venissero presi da un database e non da un array già pronto in javascript.
Ciò mi permette di poter modificare i campi direttamente sul db e non sul javascript, quindi chiunque può farlo costruendo un semplice editor.
Alcune parti del Javascript che ho usato le ho prese dal web e le ho modificate in base alle mie esigenze, il resto l'ho realizzato da zero.
L'esempio che voglio portare è:
- scelgo un continente sulla prima select
- popolo la seconda select con gli stati appartenenti al continente che ho scelto nella prima select
cosa ho usato:
- database in MySQL
- PHP
- Ajax
Non ho molta dimestichezza con Ajax, ma ho capito come funziona, girovagando su internet e studiando l'ogetto "XMLHttpRequest", fondamentale per realizzare uno script del genere.
La prima cosa che ho fatto è stato il disegno del database, con la seguente struttura:
nome database: test
nome tabella: l1 (contiene i continenti, ecco il DUMP):
nome tabella: l2 (contiene gli stati, ecco il DUMP):-- phpMyAdmin SQL Dump
-- version 2.10.0.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generato il: 22 Mag, 2007 at 05:10 PM
-- Versione MySQL: 5.0.37
-- Versione PHP: 5.2.1
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Struttura della tabella `l1`
--
CREATE TABLE `l1` (
`l1_id` int(11) NOT NULL auto_increment,
`l1_name` text collate latin1_general_ci NOT NULL,
`l1_link` text collate latin1_general_ci NOT NULL,
`l1_order` int(11) NOT NULL,
PRIMARY KEY (`l1_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=6 ;
--
-- Dump dei dati per la tabella `l1`
--
INSERT INTO `l1` VALUES (1, 'America', '', 100);
INSERT INTO `l1` VALUES (2, 'Europa', '', 200);
INSERT INTO `l1` VALUES (3, 'Asia', '', 300);
INSERT INTO `l1` VALUES (4, 'Oceania', '', 400);
INSERT INTO `l1` VALUES (5, 'Africa', '', 500);
Successivamente, ho realizzato 4 pagine in php:-- phpMyAdmin SQL Dump
-- version 2.10.0.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generato il: 22 Mag, 2007 at 05:10 PM
-- Versione MySQL: 5.0.37
-- Versione PHP: 5.2.1
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Struttura della tabella `l2`
--
CREATE TABLE `l2` (
`l2_id` int(11) NOT NULL auto_increment,
`l2_name` text collate latin1_general_ci NOT NULL,
`l2_link` text collate latin1_general_ci NOT NULL,
`l2_order` int(11) NOT NULL,
`l2_l1id` int(11) NOT NULL,
PRIMARY KEY (`l2_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=9 ;
--
-- Dump dei dati per la tabella `l2`
--
INSERT INTO `l2` VALUES (1, 'Giappone', '', 100, 3);
INSERT INTO `l2` VALUES (2, 'Cina', '', 200, 3);
INSERT INTO `l2` VALUES (3, 'Mongolia', '', 300, 3);
INSERT INTO `l2` VALUES (4, 'Stati Uniti', '', 100, 1);
INSERT INTO `l2` VALUES (5, 'Canada', '', 200, 1);
INSERT INTO `l2` VALUES (6, 'Messico', '', 300, 1);
INSERT INTO `l2` VALUES (7, 'Italia', '', 100, 2);
INSERT INTO `l2` VALUES (8, 'Spagna', '', 200, 2);
- inc/conn.inc.php (pagina di connessione al database)
- inc/class/select.class.php (pagina dei metodi di selezione dei campi)
- get.php (pagina di iterazione con il javascript)
- index.php (pagina di visualizzazione esempio)
ecco il codice relativo alle 4 pagine (ovviamente da 4 pagine se ne può fare anche una o due, ma io per comodità ho scelto di separare il codice):
pagina "inc/conn.inc.php":
pagina inc/class/select.class.php:<?php
// Inizio - Connessione DataBase
$host = 'localhost';
$login = 'root';
$password = 'password';
$db = 'test';
$conn = mysql_connect($host,$login,$password);
mysql_select_db($db,$conn);
// Fine - Connessione DataBase
?>
pagina "get.php":<?php
class select{
function select(){
}
function getL1($id=''){
if(!empty($id)){
$sSQL = "SELECT * FROM l1 WHERE l1_id = $id";
}else{
$sSQL = "SELECT * FROM l1 Order by l1_order";
}
$ris = mysql_query($sSQL);
while($row = mysql_fetch_assoc($ris)){
$list[] = array('l1_id' => $row["l1_id"],
'l1_name' => $row["l1_name"]);
}
return $list;
}
function getL2($id){
$sSQL = "SELECT * FROM l2 WHERE l2_l1id = $id Order By l2_order";
$ris = mysql_query($sSQL);
while ($row = mysql_fetch_assoc($ris)) {
$list[] = array('l2_id' => $row["l2_id"],
'l2_name' => $row["l2_name"]);
}
return $list;
}
function getL3($id){
$sSQL = "SELECT * FROM l3 WHERE l3_l2id = $id Order By l3_order";
$ris = mysql_query($sSQL);
while ($row = mysql_fetch_assoc($ris)) {
$list[] = array('l3_id' => $row["l3_id"],
'l3_name' => $row["l3_name"]);
}
return $list;
}
}
?>
pagina "index.php":<?
include('inc/conn.inc.php');
include('inc/class/select.class.php');
$id = $_REQUEST['id'];
$obj = new select();
$l1 = $obj->getL1($id);
$Js = '';
for($x=0; $x<count($l1); $x++){
$l2 = $obj->getL2($l1[$x]['l1_id']);
for($y=0;$y<count($l2);$y++){
if($y < (count($l2)-1)){
$end = ",";
}else{
$end = "";
}
$Js .= $l2[$y]['l2_id']."-".$l2[$y]['l2_name'].$end;
}
}
//echo "text";
echo $Js;
?>
Spero di non essermi dimenticato di qualcosa...<?
include('inc/conn.inc.php');
include('inc/class/select.class.php');
$obj = new select();
$l1 = $obj->getL1();
?>
<!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" lang="it">
<head>
<title>Select dinamiche con dati provenienti da Database</title>
<script type="text/javascript">
var http = createRequestObject();
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
function loading(){
var id = document.getElementById('l1').value;
http.open('GET','get.php?id='+id, true);
http.onreadystatechange = getState;
http.send(null);
}
function getState(){
var newOption;
var where = (navigator.appName == "Microsoft Internet Explorer") ? -1 : null;
var State = document.getElementById('l2');
while (State.options.length) {
State.remove(0);
}
id = document.getElementById('l1').value;
if(id == 'sel'){
document.getElementById('l2').disabled = true;
newOption = document.createElement("option");
newOption.value = 'sel';
newOption.text = 'Seleziona uno Stato:';
State.add(newOption, where);
}else{
if(http.readyState == 4){
if (http.status == 200) {
var response = http.responseText;
if(response == ''){
document.getElementById('l2').disabled = true;
newOption = document.createElement("option");
newOption.value = 'sel';
newOption.text = 'Nessuna voce';
State.add(newOption, where);
}else{
coppia = response.split(',');
max = coppia.length;
newOption = document.createElement("option");
newOption.value = 'sel';
newOption.text = 'Seleziona uno Stato:';
State.add(newOption, where);
for(x=0;x<max;x++){
val = coppia[x].split('-');
newOption = document.createElement("option");
newOption.value = val[0];
newOption.text = val[1];
State.add(newOption, where);
}
document.getElementById('l2').disabled = false;
}
}
}
}
}
</script>
</head>
<body>
<form name="form">
<div id="content">
<div id="label1">
Select 1
</div>
<div id="select1">
<select name="l1" id="l1" onchange="loading()">
<option value="sel" selected="selected">Seleziona un Continente:</option>
<?
for($x=0;$x<count($l1);$x++){
?>
<option value="<?=$l1[$x]['l1_id']?>"><?=$l1[$x]['l1_name']?></option>
<?
}
?>
</select>
</div>
<div id="label2">
Select 2
</div>
<div id="select2">
<select name="l2" id="l2" disabled>
<option value="sel" selected="selected">Seleziona uno Stato:</option>
</select>
</div>
</div>
</form>
</body>
</html>
Conclusione:
Posto tutto il codice perchè mi piace condividerlo (viva l'Open Source) e perchè ritengo che, se pur funzionante (l'ho testato solo con Explorer), sicuramente può essere migliorato; ripeto, è la prima cosa che faccio in Ajax, quindi si accettano consigli e migliorie su questo argomento.
Inoltre, tengo a precisare che lo script è rivolto a coloro che hanno già dimestichezza con php e che la discussione va fatta solo ed esclusivamente su argomenti inerenti ad Ajax.
Saluti a tutti, Max