Problem with AJAX, PHP, Mysql select dependents

Asked

Viewed 249 times

0

Good afternoon! I am facing a problem in linking 2 select. I’ve followed a lot of tutorials, but none solved.

    <?php include ('conection.php'); ?>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $('#estados').on('change', function(){
                    var estadoid = $(this).val();
                    if(estadoid){
                        $.ajax({
                            type:'POST',
                            url:"ajax.php",
                            data:'estado_id='+estadoid,
                            success: function(html) {
                                $('#cidades').html(html);
                            }
                        });
                    }else{
                        $('#cidades').html('<option value="">Escolha sua Cidade</option>'); 
                    }
                });
            });
        </script>

        <style type="text/css">
            .form-control {
                margin-top: 1rem;
                margin-bottom: 2rem;    
            }


        </style>


</head>

<body>


<div class="container">
    <div class="row">
        <div class="col-xs-4 col-xs-offset-4"> 
            <h1>Cidade Escolha</h1>
            <form class="text-center" method="get" enctype="multipart/form-data" action="">
                <div class="form-group">

                    <select class="form-control" id="estados" name="estados">
                        <option>Escolha seu Estado</option>
                        <?php 


                            $query = "select * from estados;";
                            $dt = mysqli_query($conn, $query);

                            while ($row = mysqli_fetch_array($dt)){
                            ?>
                            <option value="<?php echo $row['estado_id'];?>"><?php echo $row['nome'];?></option>
                            <?php }; ?>

                    </select>
                    <select class="form-control" id="cidades" name="cidades">
                        <option value="">Escolha sua Cidade</option>
                    </select>
                    <input type="text" name="nome" placeholder="Nome">
                    <input type="submit" name="submit" placeholder="enviar">
                </div>
            </form>
        </div>
    </div>
</div>






    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

    <script src="js/javascripts/locastyle.js"></script>

    <script src="js/bootstrap.min.js"></script>                   
</body>
</html>

The file connecting to the database

<?php   
$host = "localhost";
$user = "root";
$pas = "";
$banco = "brasil";
$conn = mysqli_connect($host,$user,$pas);
$db = mysqli_select_db($conn, $banco);
$charset = 'utf8';
mysqli_set_charset ($conn, $charset);  ?>

The ajax code

<?
include 'conection.php';

if(!empty($_POST['estado_id'])){
    $query = "SELECT * FROM cidades WHERE estado_id = ".$_POST['estado_id']." AND status = 1 ORDER BY nome ASC;";
    $dt = mysqli_query($conn, $query);
    $rowcount = mysqli_num_rows($dt);

    if ($rowcount >0) {                 
        while ($row = mysqli_fetch_assoc($dt)){
            echo '<option value="'.$row['cidade_id'].'">'.$row['nome'].'</option>';
        };

    }else{
        echo '<option value="">Cidade não Disponível</option>'; 
    }
    };
   ?>

Upshot: inserir a descrição da imagem aqui

Please help me out

  • I think we’re missing a ? in the data:'estado_id='+estado_id.Try to put the ? at the beginning of estado_id. How so: data: '?estado_id='+estado_id.

  • If you’re sending with post, you don’t need to concatenate like this data:'estado_id='+estadoid, just use it like this: data: {estado_id: estadoid},. And there is a cleaner way to feed select option using jquery

1 answer

0


Good afternoon,

I found a problem and I will pass on what and how I managed to solve and rewrite with my taste to concatenate.

In return in ajax.php, change the first line to <?, for <?php , when you pass the PHP opening just as <? this means pro php a same thing as an echo, so it received the whole code as a return.

In this same file I created a variable to receive this return in string, thus:

$str = '';
while ($row = mysqli_fetch_assoc($dt)){
    $str .= "<option value='{$row['cidade_id']}'>{$row['nome']}</option>";
};
echo $str;

for easy reading and visibility I used this writing to concatenate in the creation of options within the while,

"<option value='{$id}'>{$nome}</option>";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.