Change select element value (Ajax + php) with innerHTML

Asked

Viewed 949 times

3

Hello, I’m doing the famous combo of state carries city. Everything is working perfectly, as I will debug in my script, until the moment that must change the value of select (options returned from the function). Follow my code (index.php):

<div class="form-group">
    <label class="col-md-4 control-label col-xs-12" for="Endereco">Endereço*</label>
    <div class="col-md-1 col-xs-4">
        <select class="selectpicker" data-width="auto" id="estado" name="estado">
    <?php
            $query = "SELECT SIGLA, CODIGO FROM estado ORDER BY TX_SIGLA";
            $result = mysqli_query($conectar, $query);
            while ($resultado = mysqli_fetch_assoc($result)) { ?>
                <option value="<?php echo $resultado['CODIGO']; ?>"><?php echo $resultado['SIGLA']; ?></option>
    <?php   } ?>  

        </select>
    </div>    

    <div class="col-md-3  col-xs-4">
        <select data-width="auto" id="municipio" name="municipio" class="selectpicker">
            <option value="0" disabled="disabled">Escolha o estado</option>
        </select>
    </div>
</div>

Code (city.php):

<?php
if (isset($_POST["cd_estado"])) {

    $cod_estado = $_POST["cd_estado"];
    $query = "SELECT NOME, CODIGO FROM municipio WHERE ESTADO = '$cod_estado' ORDER BY NOME";
    $result = mysqli_query($conectar, $query);

    while ($resultado = mysqli_fetch_assoc($result)) {
        echo '<option value="' . $resultado['CODIGO'] . '">' . $resultado['NOME'] . '</option>';
    }
} else {
    echo "<option value='0'> Sem cidade </option>";
}
?>

Script:

<script>
$(document).ready(function() {

    $("#estado").change(function() {

        $("#municipio").html('<option value="0">Carregando...</option>');

        var est = document.getElementById("estado").value;

        $.ajax({
            type: 'post',
            url: 'cidade.php',
            data: {
                cd_estado: est
            },
            success: function(data) {
                document.getElementById("municipio").innerHTML = data;
                console.log(data);
            }
        });

    });
});
</script>

I have tried to change the value of select "municipality" with the following alternatives:

$("#municipio").html(data);
$("#municipio").append(data);
document.getElementById("municipio").innerHTML = data;
$("select[name=municipio]").html(data);

None works. But in "console.log(data);" the value is being returned correctly. What am I doing wrong?

  • How is the return coming data in the Ajax function? <option value="codigo_cidadex">Cidade X</option> ?

  • Yes, it is returning correctly. My problem is not being able to change the content of Div. Not even with the value <option value="codigo_cidadex">Cidade X</option> within the script itself.

  • I’m thinking it might be something with Bootstrap itself, but I still don’t know what it is. Because I tested my code on a clean page, no framework, and it works in every way.

4 answers

0

Hello, I would change some things, simple things. In your PHP I would return an array of cities, it would look something like this:

<?php
$response = [];
if (isset($_POST["cd_estado"])) {

    $cod_estado = $_POST["cd_estado"];
    $query = "SELECT NOME, CODIGO FROM municipio WHERE ESTADO = '$cod_estado' ORDER BY NOME";
    $result = mysqli_query($conectar, $query);

    while ($resultado = mysqli_fetch_assoc($result)) {
        $response[$resultado['CODIGO']] = $resultado['NOME'];
    }
} else {
    $response[0] = "Sem Cidade";
}
echo json_encode($response);
?>

In the javascript file, I would do as follows:

<script>
    $(document).ready(function() {

        $("#estado").change(function() {

            $("#municipio").html('<option value="0">Carregando...</option>');

            var est = document.getElementById("estado").value;

            $.ajax({
                type: 'post',
                url: 'cidade.php',
                dataType: `json`,
                data: {
                    cd_estado: est
                },
                success: function(data) {
                    $("#municipio").empty();
                    Object.keys(response).forEach((index) => {
                        if (typeof index != undefined) {
                            var option = response[index];
                            var valueOption = Object.keys(response[index])[0];
                            var textOption = Object.values(response[index])[0];
                            $("#municipio").append(new Option(textOption, valueOption));
                        }
                    })
                }
            });

        });
    });
</script>

0

To insert options in your select do as follows:

municipios = document.getElementById('municipio');

municipios.options[municipios.options.length] = new Option('Texto', 'Valor');

and to reset the values just use:

municipios.options.length = 0;
  • Thank you for your reply. In this case I tried to send two php variables (city.php) via: echo json_encode($return); where $return is an array with the database data, and in the script receive via var result = JSON.parse(data); . But I couldn’t.

  • Almer, your suggestion did not work. Although I can solve my problem with Json, you are not changing the options.

0

I also tried this way, with Get method:

    function getCity(state_id) {
    if (window.XMLHttpRequest) {
    xmlhttp3 = new XMLHttpRequest();
  } else { 
    xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
  }
  console.log(state_id);
  debugger;
  xmlhttp3.onreadystatechange=function() {
    if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
      document.getElementById("cityList").innerHTML=xmlhttp3.responseText;
      debugger;
    }
  }
  xmlhttp3.open("GET","cidade.php?cd_estado="+state_id,true);
  xmlhttp3.send();
  console.log(xmlhttp3);
  debugger;
}

However, I could not change the content of Div. It would be a problem to be using Bootstrap?

0

I’ve had a similar problem, and if it’s the same as mine, your problem is in the Selectpicker refresh and not the return, I’m assuming you’re using the Selectpicker(bootstrap-select). See if it helps you, I’ve made some improvements to your request.

In your code the return is in HTML, so I added the dataType: 'HTML', also put the variable $this_estado it enables you to access the elements by navigating the DOM, in this case it assumes the value of the absolute path of your element #estado.

I also added the beforeSend, that helps you set up a more real load, based on the return time of your code, if you want to see it in quick connections put a sleep(1), at the top of your file cidade.php.

And the big point here is $('.selectpicker').selectpicker('refresh'); updating the Selectpicker to show your data on the screen.

NOTE: Does not understand the pq of innerHTML, but if it is mandatory for some reason it is only you adapt, but as you are already using jquery the code below works the same way.

<script>
$(document).ready(function() {

    $("#estado").change(function(){

        //Pega o seletor do elemento;
        var $this_estado = $(this); 

        // Pega o valor do estado selecionado;
        var est = $this_estado.("#estado").val();

        $.ajax({
            type: 'POST',
            dataType: 'HTML',
            url: 'cidade.php',
            data: { cd_estado: est },
            beforeSend: function(){

                // Movi está opção para cá
                // O beforeSend é executado antes do retorno
                // Ótimo para criar animações de loading
                $this_estado.html('<option value="0">Carregando...</option>');

            },
            success: function(cidades){

                // Insere no select cidades os dados vindos da consulta.
                $('#municipio').html(cidades);

                // Atualize o selectpicker para os novos valores que foram inseridos nele.
                $('.selectpicker').selectpicker('refresh');

            }
        });

    });
    
});
</script>

Browser other questions tagged

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