依赖下拉列表

I am newbie to JQuery Ajax. May i know how to create a PHP to read the subcategory list depends on the selected maincategory? So far i had create a jQuery AJAX in my asset_add.php

<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
    $('#main_category').on('change',function(){
        var categoryNAME = $(this).val();
        if(categoryNAME){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'ac_maincategory='+categoryNAME,
                success:function(html){
                    $('#sub_category').html(html);
                }
            }); 
        }else{
            $('#sub_category').html('<option value="">Select main category first</option>');
        }
    });
});
</script>

and for HTML,

<tr>
    <td valign=top><strong>MAIN CATEGORY</td>
    <td><select name="main_category" id="main_category" onchange="this.form.submit()" required>
        <?php
            $sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
            $result = mysqli_query($conn, $sql);
            $count=mysqli_num_rows($result);
        ?>
                <option value=""></option>
        <?php
                if($count > 0)
                {
                    while ($rs = mysqli_fetch_array($result)) 
                    {
                        $ac_maincategory  = $rs["ac_maincategory"];
                        $ac_id            = $rs["ac_id"];           
        ?>
                        <option value="<?=$ac_id?>"><?=$ac_maincategory?></option>
        <?php
                    }
                }
        ?>
        </select>
    </td>   
    </tr>

    <tr>
    <td valign=top><strong>SUB CATEGORY</td>
    <td><select id= "sub_category" name="sub_category"  autocomplete="off"/ required>
        <option value=""></option>
        </select>
    </tr>

while in my ajaxData.php

<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();

if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
    $sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
    $result = mysqli_query($conn, $sql);
    $count=mysqli_num_rows($result);
    if($count > 0)
    {
        echo '<option value="">Select Subcategory</option>';
        while ($rs = mysqli_fetch_array($result)) 
        {
            $ac_subcategory  = $rs["ac_subcategory"];
            $ac_id            = $rs["ac_id"];
            echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
        }
    }
}

?>

However, when i choose a maincategory in asset_add.php, nothing shown in subcategory. Can anyone tell me which part i do wrong? Thanks for help

Seems you are replacing whole div with $('#sub_category').html(html); so there is only options printed on the view

You can solve it by replacing the line

$('#sub_category').html(html);

to

$('#sub_category').append(html);

Or Just replace this code in ajaxData.php , S

//Include database configuration file
require("config.php");
$conn = dbconnect();

if(empty($_POST["ac_maincategory"])){
    die("category is empty");
}

$sql = "SELECT * FROM asset_category WHERE ac_maincategory = " . $_POST['ac_maincategory'];
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0)
{
    echo '<select id= "sub_category" name="sub_category"  autocomplete="off"/ required>';
    echo '<option value="">Select Subcategory</option>';
    while ($rs = mysqli_fetch_array($result))
    {
        $ac_subcategory     = $rs["ac_subcategory"];
        $ac_id              = $rs["ac_id"];
        echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
    }

    echo "</select>";
}

<?php
//.....
//you sql......$result
//.....

if($_POST['ac_maincategory']) {

    //this is test
    if($_POST['ac_maincategory']=="aaa"){
        $result=array("k1"=>"v1","k2"=>"v2");
    }else{
        $result=array("kk1"=>"v11","kk2"=>"v22");
    }
    $str = '<option value="">Select Subcategory</option>';
    foreach ($result as $k => $v) {
        $str .= '<option value="' . $k . '">' . $v . '</option>';
    }
    echo $str;exit;
}
?>
<html>
<head></head>
<body>
<div>
    <select id="main_category">
        <option value=""></option>
        <option value="aaa">aaa</option>
        <option value="bbb">bbb</option>
    </select>
</div>
<div>
    <select id="sub_category">
        <option value=""></option>
    </select>
</div>

</body>
</html>
<script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
<script>
    $("#main_category").change(function () {
        var categoryNAME=$(this).val();
        $.ajax({
            type:'POST',
            url:'',
            data:{"ac_maincategory":categoryNAME},
            success:function(html){
                $('#sub_category').html(html);
            }
        });
    })

</script>

test image

https://i.stack.imgur.com/oJLKo.png

https://i.stack.imgur.com/oIw03.png

https://i.stack.imgur.com/vQQrz.png

</div>

this is simple question and should be fixed ASAP. but idk why still not solved yet.

so, please try this

html

  • remove onchange attribute (remove native js event trigger style with jquery style)
  • optional:
    • fix several unclosed tag html
    • remove unrecomended PHP writing style

into this

<tr>
    <td valign="top"><strong>MAIN CATEGORY</strong></td>
    <td>
        <select name="main_category" id="main_category" required>
            <option value=""></option>
            <?php
                $sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
                $result = mysqli_query($conn, $sql);
                $count=mysqli_num_rows($result);
                if($count > 0)
                {
                    while ($rs = mysqli_fetch_array($result)) 
                    {
                        echo '<option value="'. $rs["ac_id"] .'">'.$rs["ac_maincategory"].'</option>';
                    }
                }
            ?>
        </select>
    </td>   
</tr>

<tr>
    <td valign="top"><strong>SUB CATEGORY</strong></td>
    <td>
        <select id= "sub_category" name="sub_category"  autocomplete="off" required>
            <option value="">Select main category first</option>
        </select>
    </td>
</tr>

jquery

  • change on('change') with change() // possible dont know when to use on or not
  • change wrong comparasion on categoryNAME
  • optional:
    • change serialize data style using data {} //better for newbie to study

into this

<script>
    $(function(){
        $('#main-category').change(, function(){
            var categoryNAME = $(this).val();
            if(categoryNAME != ''){
                $.ajax({
                    type:'POST',
                    url:'ajaxData.php',
                    data:{ac_maincategory: categoryNAME},
                    success:function(html){
                        $('#sub_category').html(html);
                    }
                }); 
            }else{
                $('#sub_category').html('<option value="">Select main category first</option>');
            }

        })
    });
</script>

PHP

  • reposition default sub-category value out of $count comparasion

into this

<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();

if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
    $sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
    $result = mysqli_query($conn, $sql);
    $count=mysqli_num_rows($result);
    echo '<option value="">Select Subcategory</option>';
    if($count > 0)
    {
        while ($rs = mysqli_fetch_array($result)) 
        {
            $ac_subcategory  = $rs["ac_subcategory"];
            $ac_id            = $rs["ac_id"];
            echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
        }
    }
}

?>