使用AJAX和PHP来改变组合框选择

时间:2015-08-26 15:42:59

标签: javascript php ajax combobox

我整个上午一直在努力和奋斗让我的组合框正确更新。一旦用户在第一个框中选择并选择我想要填充第二个框,其中包含适用于所选第一个选项的选项。我已经编写了一个单独的php脚本来接受所选的选项,并从sql数据库中提取适用的返回值。这个脚本在单独运行时工作正常,但我无法使用AJAX在javascript中工作

PHP:

<?php
$name=$_GET['name'];

// select box option tag
$selectBoxOption1 = ''; 

// connect mysql server
$con=mysql_connect('localhost', 'root', '');
if (!$con) { 
    die('Could not connect: ' . mysql_error()); 
}
mysql_select_db('mysql',$con);
$sql1 = "SELECT DISTINCT bike_type FROM bc_fit WHERE name='$name'";
$result1 = mysql_query($sql1);

// play with return result array 
while($row = mysql_fetch_array($result1)){   
    $selectBoxOption1 .="<option value = '".$row['bike_type']."'>".$row['bike_type']."</option>"; 
}
// return options
echo $selectBoxOption1;
?>

Javascript(#nap2是当前框,#nap 4是下一个):

$("#nap2").change(function(event){
    var selected = $(this).find('option:selected').text()
    $('#nap4').removeAttr('disabled');
    $('#nap4').empty();
    //need to get options based upon nap 2 choice by calling php script with selected and returning all unqiue bike under that name

    var options4;
    $.ajax({ 
    type: "GET",
    url: 'getbiketype.php', 
    data: "name"=selected,
    success:  function(data) {
      options4 = data;
    }
    });
    $('#nap4').append($(options4));
});

1 个答案:

答案 0 :(得分:1)

你的jQuery中有一些问题:

<select id="nap2" class="napkeeComponent napkeeCombobox">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="2">Three</option>
</select>
<select id="nap4" class="napkeeComponent napkeeCombobox" disabled>
</select>
<script>

$(document).ready(function() {
    $("#nap2").change(function(event){
        // You just get the value of selected input
        // You don't need to find anything because you've already selected it
        var selected = $(this).val();
        $('#nap4').removeAttr('disabled');
        $('#nap4').empty();
        $.ajax({ 
                type: "GET",
                url: 'getbiketype.php',
                // Your creation of the data object is incorrect
                data: { name: selected },
                success:  function(data) {
                    console.log(data);
                    // Here just append the straight data
                    $('#nap4').append(data);
                }
        });
    });
});
</script>