Pass variable jquery to search subcategory

0

I'm doing two select, the category and subcategory. Both via MySQL. I would like that when selecting the category, pass the category ID to the Subcategory.

$rsCategoria    = $conexao->query("SELECT * FROM categoria WHERE idioma = 'pt-br' ");
$rsSubcategoria = $conexao->query("SELECT * FROM categoriasub WHERE id_categoria = '{$id_categoria}' AND idioma = 'pt-br' ");

.

<select id="categoria" name="categoria" class="input form-control col-lg-10" required>
                        <option value="" selected="selected">Selecione</option>
                        <?php while ($rowCategoria = $rsCategoria->fetch_assoc()) {?>
                            <option value="<?php echo $rowCategoria['ID_Categoria'] ?>"><?php echo $rowCategoria['nome'] ?></option>
                        <?php } ?>
                    </select>

                    <select id="subcategoria" name="subcategoria" class="input form-control col-lg-10" style="margin-top: 20px;">
                        <option value="" selected="selected">Selecione</option>
                        <?php while ($rowSubcategoria = $rsSubcategoria->fetch_assoc()) {?>
                            <option value="<?php echo $rowSubcategoria['ID_Categoria'] ?>"><?php echo $rowSubcategoria['nome'] ?></option>
                        <?php } ?>
                    </select>

What would be the best way to find the subcategory?

    
asked by anonymous 31.07.2017 / 22:40

1 answer

1

I have been able to do it, I will leave it registered here for anyone who has the same doubts as I do.

SELECT

$rsCategoria    = $conexao->query("SELECT * FROM categoria");

HTML

<select id="categoria" name="categoria" required>
    <option value="" selected="selected">Selecione</option>
        <?php while ($rowCategoria = $rsCategoria->fetch_assoc()) {?>
            <option value="<?php echo $rowCategoria['ID_Categoria'] ?>"><?php echo $rowCategoria['nome'] ?></option>
        <?php } ?>
</select>

<select id="subcategoria" name="subcategoria" required>
    <option>Selecione acima primeiro</option>
</select>

JQUERY

$(document).ready(function () {
    $("select[name=categoria]").change(function(){
        $("select[name=subcategoria]").html('<option value="">Carregando...</option>');

        $.post("inc_subCategoria.php",
            {ID_Categoria:$(this).val()},
            function(valor){
                $("select[name=subcategoria]").html(valor);
           }
        )
    })
});

inc_subCategory.php

<?php
include 'conexao.php';

$rs = $conexao->query("SELECT * FROM categoriasub WHERE id_categoria = '{$_POST['ID_Categoria']}' AND idioma = 'pt-br' ");

    echo '<option value="" selected="selected">Selecione</option>';
while($row = $rs->fetch_assoc()) {
    echo '<option value="'.$row['ID_Subcategoria'].'">'.$row['nome'].'</option>';
}

I hope this can help someone. If it helped mark up.

    
01.08.2017 / 00:25