Pass value to variable

Asked

Viewed 209 times

0

I need the variable $idestados receive status id value when an option is selected but I’m getting beat up by ajax and jquery so I want to know if you have a better option to do this.

The $anuncio is a class that selects in the table bdd states through the selEstados() and returns an array with all the information, it also has the selCidades(id_estado) which does the same with bdd’s cities table but it receives the state id as parameter:

 <select name="estados" id="estados" ">                                    
    <option value="0" selected disabled>Selecione um estado</option>
    <?php 
    $estados=$anuncio->selEstados();
    foreach ($estados as $estado){
       echo '<option value="'.$estado['id'].'">'.$estado['sigla'].'- 
     '.$estado['nome'].'</option>';
    }

    ?>
 </select><br>
 <select name="cidades" id="cidades" >
    <option value="0">Selecione um estado primeiro...</option>
    <?php
        $cidades=$anuncio->selCidades($idestados);
        foreach ($cidades as $cidade){                                            
            echo '<option value"'.$cidade['nome'].'">'.$cidade['nome'].'</option>';
        }
    ?>

 </select>

this code

require_once "anuncio.php";
$anuncio =  new anuncio();
$estados= $anuncio->selEstados();
print_r($estados);

produces this result: 'array' print_r($estados);

likewise the

require_once "anuncio.php";
$anuncio =  new anuncio();
$cidades= $anuncio->selCidades();
print_r($cidades);

will produce the same effect but with city names and state id instead of the acronym

inserir a descrição da imagem aqui

  • Edit the question and post the rest of your code to help.

  • After PHP processes the information, it is not possible to change its variables. For this you should use AJAX (post as you are trying) or sending the information via a form.

  • I deleted the code I had made when it didn’t work, could you give me an example of how it would work based on the code I passed up there?

3 answers

1

could give me an example of how it would work based on the code I passed up there?

Form file (.php):

<?php
    // INICIALIZAÇÃO DAS VARIÁVEIS:
    $estados = array("RIO DE JANEIRO", "ESPÍRITO SANTO", "MINAS GERAIS", "BAHIA");
?>

<!-- CARREGAMENTO DO JQUERY -->
<script src="scripts/jquery-1.12.0.min.js" type="text/javascript"></script>

<select name="estados" id="estados">
    <option value="0" selected disabled>Selecione um estado</option><?php
    //$estados=$anuncio->selEstados();
    foreach ($estados as $estado) {
        echo "<option value=\"".$estado."\">".$estado."</option>";
    } ?>
</select>

<br>

<select name="cidades" id="cidades">
    <option value="0">Selecione um estado primeiro...</option>
</select>

<script type="text/javascript">
    $(function(){
        $('#estados').on('change', function(){
            $.ajax({
                url: 'getcidades.php',
                data: 'estado=' + $('#estados').val(),
                dataType: "json",
                method: 'POST',
                cache: false,
                beforeSend: function() {
                    console.log($('#estados').val());
                },
                success: function(data) {
                    let options;
                    $.each(data, function(chave, valor){
                        options += "<option value=\""+valor+"\">"+valor+"</option>";
                    });
                    $('#cidades').html(options);
                },
                error: function(e) {
                    console.log(e);
                }
            });
        });
    });
</script>

File that handles the requisition of Ajax (getcities.php):

<?php
    header('Content-Type: application/json');

    if ($_POST['estado']) {
        switch($_POST['estado']) {
            case "RIO DE JANEIRO":
                $cidades = array("RIO DE JANEIRO", "SÃO GONÇALO", "NITERÓI");
                break;
            case "ESPÍRITO SANTO":
                $cidades = array("VITÓRIA", "GUARAPARY", "VILA VELHA");
                break;
            case "MINAS GERAIS":
                $cidades = array("BELO HORIZONTE", "VIÇOSA", "JUIZ DE FORA");
                break;
            case "BAHIA":
                $cidades = array("SALVADOR", "PORTO SEGURO", "JUAZEIRO");
                break;
        }
        echo json_encode($cidades);
    }
  • Of course it’s quite simple! It’s just a copy for you to adapt as your need...

  • Note that for this example we used the jQuery in version 1.12! If you use a newer version, you should be aware of depreciation and successive removal of attributes success and error used in that code.

Deprecation Notice: The jqXHR.Success(), jqXHR.error(), and jqXHR.complete() callbacks are Removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.Always() Instead.

Reading recommendation: jQuery.ajax()

Special thanks to @Guilherme Costamilam by notifying and updating the code with the jQuery in version 3.

  • I put some more information in the question

  • So, you can base your code with the one I posted. Also focus on the page that handles the ajax request.

  • the code you passed doesn’t work in my example, I need to search the cities I have already registered in the database the codes you commented on mine, are the array you are creating in your need that this getCidade page receive the value of the state to use as parameter in select tried here and it didn’t work

  • *It’s just a sample for you to adapt to your needs... * and So you can base your code on the one I posted. Also focus on the page that handles the ajax request Of course you’ll have to adapt your code (That is not present in the question) to work with this code I posted...

1

The @Lipespry example illustrates exactly what you need, but sucess and error are obsolete and have changed to done and fail:

$(function(){
    $('#estados').on('change', function(){
        $.ajax({
            url: 'getcidades.php',
            data: 'estado=' + $('#estados').val(),
            dataType: "json",
            method: 'POST',
            cache: false,
            beforeSend: function() {
                console.log($('#estados').val());
            }
         }).done(function(data) {
                let options;
                $.each(data, function(chave, valor){
                    options += "<option value=\""+valor+"\">"+valor+"</option>";
                });
                $('#cidades').html(options);
        }).fail(function(e) {
                console.log(e);
        });
    });
});
  • Thanks for the reply! I even updated my attention to this update of jQuery.

0

solved like this:

<select name="estados" id="estados" title="Selecione um Estado">
    <option value="0" selected disabled>Selecione um estado</option>
    <?php
      $feachall=$anuncio->selEstados();
      foreach ($feachall as $estados){
         echo '<option value="'.$estados['id'].'">'.$estados['nome'].'</option>';
      }                      
     ?>
</select><br>
<select name="cidades" id="cidades"  >
     <option value="0">Selecione um estado primeiro...</option>


</select><br>

the script

<script>
$("#estados").on("change",function(){
let idEstado = $("#estados").val();
$.ajax({
    url: 'pega_cidades.php',
    type: 'POST',
    data:{id:idEstado},
    beforeSend: function(){

        $("#cidades").html("Carregando...");
    },
    success: function(data){

        $("#cidades").html(data);
    },
    error: function(){

        $("#cidades").html("Houve um erro ao carregar");
    }
  });
});

</script>

and the page takes cities.php

<?php
    require_once'../cerebro/conectarbdd.php';
    $db = new conectarbdd;
    $conexao=$db->conectar();
    $conexao->exec("SET CHARACTER SET utf8");
    $pegaCidades=$conexao->prepare("SELECT * FROM cidades WHERE 
    estados_id='".$_POST['id']."'" );
    $pegaCidades->execute();
    $fetchall = $pegaCidades->fetchAll();

    foreach ($fetchall as $cidades){

      echo '<option value="'.$cidades['nome'].'">'.$cidades['nome'].'</option>';
  }

Browser other questions tagged

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