Page 1 sur 1

Select liés

Posté : 05 mai 2021, 19:24
par michgoarin
Bonjour,
Je viens d'adapter le code exploré dans le tuto #lier-select-313 sur Grafikart.fr

Je ne comprends pas mon erreur et mes connaissances en javascript et jQuery sont assez limitées :

Le premier fichier "test_select_type_materiel.php" :

Code : Tout sélectionner

    <body>
    	<?php
        	require "db.class.php";
        	$DB = new DB();
        	$types = $DB->query('SELECT * FROM type_vehicule');
        	$sous_types = $DB->query('SELECT * FROM sous_type_vehicule');
        	$sousTypeByType = array();
        	foreach( $sous_types as $sous_type) {
        		$sousTypeByType[$sous_type->ID_TYPE_VEHICULE][$sous_type->ID] = $sous_type->NOM_SOUS_TYPE;
        	}
        	
        	$type_id = 0;
        	if(isset($_POST['type_vehicule'])){
        		$type_id = $_POST['type_vehicule'];
        	}
        	
        	var_dump($sousTypeByType);
    	?>
		<div class="navbar navbar-fixed-top">
		  <div class="navbar-inner">
		    <div class="container">
		      	<a class="brand" href="#">
				  Select
				</a>
		    </div>
		  </div>
		</div>

		<form method="post" action="#">

		<div class="container" style="margin-top:60px">

			<div class="row">
				<div class="span3">
					<div class="control-group">
						<label class="control-label" for="select01">Type de véhicule : </label>
						<div class="controls">
			 				<select id="type_vehicule" name="type_vehicule" size="25" data-target="id_type" data-url="sous_type.php" class="ajaxList">
			 					<?php foreach ( $types as $type ): ?>
			 						<option value="<?= $type->ID; ?>"<?= $type_id == $type->ID ? ' selected' : ''; ?>>
			 							<?= $type->TYPE_VEHICULE; ?>
			 						</option>
			 					<?php endforeach ?>
			              	</select>
			            </div>
		          	</div>
				</div>
				<div class="span3">
					<div class="control-group">
						<label class="control-label" for="select01">Sous-Type</label>
						<div class="controls">
			 				<select id="sous_type" name="sous_type" size="25" class="ajaxList" data-url="option_type.php" data-target="option_type">
			 					<option value="0">Vous devez sélectionner un sous-type de matériel</option>
			              	</select>
			            </div>
		          	</div>
				</div>
				<div class="span3">
					<div class="control-group">
						<label class="control-label" for="select01">Information Complémentaire</label>
						<div class="controls">
			 				<select id="option_type" name="option_type" size="25">
			 					<option value="0">Vous devez sélectionner une information complméentaire</option>
			              	</select>
			            </div>
		          	</div>
				</div>
			</div>

	       <input type="submit" value="Envoyer">

	       <?= var_dump($_POST); ?>

	</div>

	</form>
Le second fichier "sous_type.php" :

Code : Tout sélectionner

<?php
require 'db.class.php';
if(isset($_GET['id'])){
	$db = new DB();
	$sousType = $db->query('SELECT * FROM `sous_type_vehicule` WHERE ID_TYPE_VEHICULE=:type_vehicule',array('type_vehicule' => $_GET['id']));
	if(empty($sousType)){
		$return = array('error' => "Il n'existe pas de sous-type pour ce type de matériel sélectionnée");
	}else{
		$return = array(
			'error' => false,
			'results' => $sousType
		);
	}

}else{
	$return = array('error' => "Vous n'avez pas sélectionné le type de matériel");
}

die(json_encode($return));
?>
Le fichier app.js :

Code : Tout sélectionner

	$('.ajaxList').change(function(event){
		var select = $(this);
		var id = '#'+select.data('target');
		$.get(select.data('url'), {id:select.val()}, function(data){
			if(data.error){
				alert(data.error);
			}else{
				$(id).parents('.control-group').show();
				var target = $(id).get(0);
				target.options.length = 0;
				for(var i in data.results){
					var result = data.results[i];
					target.options[i] = new Option(result.name, result.id, false, false);
				}
			}
		},'json');
	}).each(function(){
		var select = $(this);
		var target = $('#'+select.data('target'));
		target.parents('.control-group').hide();
	});

})(jQuery);
Voici la Bdd:

Code : Tout sélectionner

--
-- Structure de la table `type_vehicule`
--

CREATE TABLE `type_vehicule` (
  `ID` int(11) NOT NULL,
  `CODE_TYPE` int(11) NOT NULL,
  `TYPE_VEHICULE` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Structure de la table `sous_type_vehicule`
--
CREATE TABLE `sous_type_vehicule` (
  `ID` int(11) NOT NULL,
  `ID_TYPE_VEHICULE` int(11) NOT NULL,
  `NOM_SOUS_TYPE` varchar(255) CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Déchargement des données de la table `type_vehicule`
--

INSERT INTO `type_vehicule` (`ID`, `CODE_TYPE`, `TYPE_VEHICULE`) VALUES
(1, 1, 'BERLINE'),
(2, 2, 'FGTTE'),
(3, 3, 'FGON'),
(4, 4, 'P.L.'),
(5, 4, 'BUS'),
(6, 5, 'SPECIAL'),
(7, 6, 'SCOOTER'),
(8, 6, 'VELO'),
(9, 7, 'TONDEUSE'),
(10, 8, 'DIVERS'),
(11, 8, 'HORS PARC');
--
-- Déchargement des données de la table `sous_type_vehicule`
--

INSERT INTO `sous_type_vehicule` (`ID`, `ID_TYPE_VEHICULE`, `NOM_SOUS_TYPE`) VALUES
(1, 1, 'VP - PETITE CITADINE - CATEGORIE  M1'),
(2, 1, 'VP - CITADINE - CATEGORIE  M1'),
(3, 1, 'VP - LUDOSPACE - CATEGORIE M1'),
(4, 1, 'VP - ROUTIERE - CATEGORIE M1'),
(5, 1, 'VP - BREACK - CATEGORIE M1'),
(6, 1, 'VP - MONOSPACE - CATEGORIE M1'),
(7, 1, 'VP - SUV - CATEGORIE M1'),
(10, 2, 'VUL - UTILITAIRE FOURGONNETTE TOLEE - CATEGORIE  N1'),
(11, 2, 'VUL - UTILITAIRE BENNE - CATEGORIE  N1'),
(12, 2, 'VUL - UTILITAIRE GROUPE FROID - CATEGORIE  N1'),
(13, 2, 'VUL - UTILITAIRE PLATEAU - CATEGORIE N1'),
(15, 3, 'VU - UTILITAIRE FOURGON TOLE - CATEGORIE  N1'),
(16, 3, 'VU - UTILITAIRE CAISSE HAYON - CATEGORIE  N1'),
(17, 3, 'VU - UTILITAIRE BENNE SIMPLE - CATEGORIE  N1'),
(18, 3, 'VU - UTILITAIRE BENNE ET GRUE - CATEGORIE  N1'),
(19, 3, 'VU - UTILITAIRE FRIGORIFIQUE - CATEGORIE  N1'),
(20, 3, 'VU - UTILITAIRE PLATEAU - CATEGORIE N1'),
(22, 4, 'CAMION - CITERNE MOINS DE 12T - CATEGORIE  N2'),
(23, 4, 'CAMION - BENNE SIMPLE MOINS DE 12T - CATEGORIE  N2'),
(24, 4, 'CAMION - BENNE ET GRUE MOINS DE 12T - CATEGORIE  N2'),
(25, 4, 'CAMION - PORTE CHAR MOINS DE 12T - CATEGORIE  N2'),
(26, 4, 'CAMION - PLATEAU MOINS DE 12T - CATEGORIE  N2'),
(27, 4, 'CAMION - GROUPE FROID MOINS DE 12 T - CATEGORIE  N2'),
(28, 4, 'CAMION - FOURGON MOINS DE 12 T - CATEGORIE  N2'),
(29, 4, 'CAMION - BETAILLERE MOINS DE 12 T'),
(30, 4, 'CAMION - CITERNE PLUS DE 12T - CATEGORIE  N3'),
(31, 4, 'CAMION - BENNE SIMPLE PLUS DE 12T - CATEGORIE  N3'),
(32, 4, 'CAMION - BENNE ET GRUE PLUS DE 12T - CATEGORIE  N3'),
(33, 4, 'CAMION - PORTE CHAR PLUS DE 12T - CATEGORIE  N3'),
(34, 4, 'CAMION - PLATEAU PLUS DE 12T - CATEGORIE  N3'),
(35, 4, 'CAMION - GROUPE FROID PLUS DE 12 T - CATEGORIE  N3'),
(36, 4, 'CAMION - FOURGON PLUS DE 12 T - CATEGORIE  N3'),
(37, 4, 'CAMION - BETAILLERE PLUS DE 12 T'),
(38, 4, 'CAMION - PORTE GRUMES PLUS DE 12T - CATEGORIE N3'),
(39, 4, 'CAMION - GRUE PLUS DE 12 T - CATEGORIE N3'),
(41, 5, 'BUS - CAPACITE SUPERIEURE A 22 PASSAGERS CLASSE I - MOINS DE 5T - CATEGORIE M2'),
(42, 5, 'BUS - CAPACITE SUPERIEURE A 22 PASSAGERS CLASSE II - MOINS DE 5T - CATEGORIE M2'),
(43, 5, 'BUS - CAPACITE SUPERIEURE A 22 PASSAGERS CLASSE III - MOINS DE 5T - CATEGORIE M2'),
(45, 5, 'BUS - CAPACITE SUPERIEURE A 22 PASSAGERS CLASSE I - PLUS DE 5T - CATEGORIE M3'),
(46, 5, 'BUS - CAPACITE SUPERIEURE A 22 PASSAGERS CLASSE II - PLUS DE 5T - CATEGORIE M3'),
(47, 5, 'BUS - CAPACITE SUPERIEURE A 22 PASSAGERS CLASSE III - PLUS DE 5T - CATEGORIE M3'),
(49, 5, 'BUS - CAPACITE INFERIEURE A 22 PASSAGERS CLASSE A - MOINS DE 5T - CATEGORIE M2'),
(50, 5, 'BUS - CAPACITE INFERIEURE A 22 PASSAGERS CLASSE B - MOINS DE 5T - CATEGORIE M2'),
(52, 5, 'BUS - CAPACITE INFERIEURE A 22 PASSAGERS CLASSE A - PLUS DE 5T - CATEGORIE M3'),
(53, 5, 'BUS - CAPACITE INFERIEURE A 22 PASSAGERS CLASSE B - PLUS DE 5T - CATEGORIE M3'),
(55, 6, 'TRACTEUR'),
(56, 6, 'REMORQUE'),
(57, 6, 'ENTRETIEN ESPACES PUBLICS'),
(58, 6, 'ENGIN DE CHANTIER'),
(59, 6, 'TONDEUSE AUTOPORTEE'),
(61, 7, 'DEUX ROUES'),
(62, 7, 'TROIS ROUES'),
(64, 8, 'DEUX ROUES'),
(65, 8, 'TROIS ROUES'),
(67, 10, 'ENTRETIEN ESPACES VERTS'),
(68, 10, 'PETITS MATERIELS 2 TEMPS'),
(69, 10, 'DISPOSITIF AUTONOME'),
(70, 10, 'LEVAGE'),
(71, 10, 'ENTRETIEN ESPACES ROUTIERS'),
(72, 10, 'REMORQUE'),
(74, 11, 'EQUIPEMENT GARAGE'),
(75, 11, 'MATERIEL NON CODE'),
(76, 11, 'LEVAGE'),
(77, 11, 'MATERIEL MOBILE'),
(78, 11, 'PONT ELEVATEUR'),
(79, 11, 'REPORT FRAIS AFFECTES');

**Ce que je veux**

Comme le précise le tuto, avec pour exemple les régions et les départements, je souhaiterai lié le select "sous_type" avec le select "type_materiel".

**Ce que j'obtiens**

L'affichage des Types de véhicule est correct mais il ne se passe rien quant à la mise à jour de l'autre select "sous_type".
Lorsque j'extrait le fichier "sous_type.php?id=4", voici ce que j'obtiens :
Lorsque je contrôle la console :

Code : Tout sélectionner

{"error":false,"results":[{"ID":"10","ID_TYPE_VEHICULE":"2","NOM_SOUS_TYPE":"VUL - UTILITAIRE FOURGONNETTE TOLEE - CATEGORIE N1"},{"ID":"11","ID_TYPE_VEHICULE":"2","NOM_SOUS_TYPE":"VUL - UTILITAIRE BENNE - CATEGORIE N1"},{"ID":"12","ID_TYPE_VEHICULE":"2","NOM_SOUS_TYPE":"VUL - UTILITAIRE GROUPE FROID - CATEGORIE N1"},{"ID":"13","ID_TYPE_VEHICULE":"2","NOM_SOUS_TYPE":"VUL - UTILITAIRE PLATEAU - CATEGORIE N1"}]}
et sur la console :

Code : Tout sélectionner

app.js:35 Uncaught TypeError: Cannot read property 'options' of undefined
    at Object.success (app.js:35)
    at o (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at w (jquery.min.js:4)
    at XMLHttpRequest.d (jquery.min.js:4)
Auriez vous une solution ? Je travail sur ce sujet depuis 4 heures sans trouver l'erreur.

Re: Select liés

Posté : 06 mai 2021, 14:05
par webmaster
Bonjour,

Le message d'erreur indique que .options n'est pas disponible dans la fonction success de l'appel ajax :
app.js:35 Uncaught TypeError: Cannot read property 'options' of undefined
at Object.success (app.js:35)

Le code correspondant doit donc etre ici :

Code : Tout sélectionner

				$(id).parents('.control-group').show();
				var target = $(id).get(0);
				target.options.length = 0;
Cela signifie que target n'est pas défini.
Et en effet, le code est étrange. Target doit etre un element select, mais il y a get(0) qui est un appel ajax en jquery.
Cela me semble incohérent.