2015-01-14 4 views
0

Я пытаюсь понять концепцию использования каскадных выпадающих списков в php-скрипте с использованием jquery. Я могу получить первое выпадающее меню, но не второе.Попытка понять концепцию каскадных выпадающих списков

Первый раскрывающийся список содержит идентификатор и имя клиента для клиентов в базе данных mysql. Второй раскрывающийся список содержит инструменты клиентов, которые связаны с идентификатором клиента, который является ключом foriegn в таблице инструментов.

Может ли кто-нибудь взглянуть на код и рассказать мне, где я могу сбиться с пути?

Это index.php

<!DOCTYPE html> 
<html> 

<head> 
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"> 
<title>Chained Select Tutorial</title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2 /jquery.min.js"></script> 
</head> 

<body> 
<?php 
include('dbconnect.php'); 
$con=mysqli_connect($host,$user,$password,$db); 
// An array of options for the first select box. 
$result = mysqli_query($con, "SELECT * FROM customers ORDER BY Customer Asc "); 

// Displays the posted info 
if(isset($_POST['submit'])) 
{ echo '<pre>'; print_r($_POST); echo '</pre>'; } 
?> 
<form action="" method="post"> 
<select id="cust" name="cust"><!-- Make sure to give the select box a id, this will make it much easier to target with jquery. --> 
<?php 
// Build the options for the first select box 
while($row = mysqli_fetch_array($result)){ echo '<option value="'.$row[Cust_ID].'">'.$row[Customer].'</option>'; } 
?> 
</select> 
<select id="models" name="models"><!-- Make sure to give the select box a id, this will make it much easier to target with jquery. --> 
</select> 
<input type="submit" name="submit" value="Submit"> 
</form> 

<script> 
$('#cust').change(function(){ //Basically saying when the first select box changes values run the function below. 
var cust = $(this).val(); // Grab the value of the selection to send to the select-request.php via ajax 
$.post('select-request.php', {cust:cust}, function(data){ // Run a ajax request and send the var make as a post variable named "make" and return the info in the "data" var. 
    $('#models').html(data); // Have jquery change the html within the second select box with the "data" we got back from the ajax request. 
}); 
}); 
</script> 

</body> 

</html> 

и это выбрать-request.php

<?php 
error_reporting(E_ALL); //Remove this line for production, it simply will allow php to display any errors 


//We check to see if the "cust" post has come through before we do any processing. 
if(isset($_POST['cust'])) 
{ 
$con=mysqli_connect($host,$user,$password,$db); 
$result1 = mysqli_query($con, "SELECT Inst_Name FROM instruments WHERE Cust_ID='$_POST[cust]'"); 
while($row = mysqli_fetch_array($result1)){ echo '<option value="'.$row[Inst_Name].'">'.$row[Inst_Name].'</option>'; 

} 
?> 

Может кто-нибудь пожалуйста, скажите мне, где я заблудился?

+0

Включили ли вы 'dbconnect.php' в свой файл' select-request.php'? Вы также должны включить отображение ошибок и проверить точный ответ в консоли. – jeroen

+0

У меня не было dbconnect, включенного в select-request.php. Я теперь включил его, но безрезультатно, никаких результатов. – phpnoobie

+0

Любые сообщения в консоли? Вы не разместили свой javascript в разделе, подготовленном документами, чтобы вы могли получить ошибки, которые jQuery еще не определен. – jeroen

ответ

0

Не зная вывода на вашей консоли, я предполагаю, что jQuery берет первую строку в качестве вывода из вашего php-скрипта. Другими словами, он получает только первое ... что select-request.php является эхом. Попробуйте следующее:

while($row = mysqli_fetch_array($result1)){ 
    $returnable .= '<option value="'.$row[Inst_Name].'">'.$row[Inst_Name].'</option> '; 
} 
echo json_encode($returnable); 
Смежные вопросы