How to take the value of php Session and in the select field mark as Selected through ajax?

Asked

Viewed 50 times

-1

Hi, anyone who can help me would be great. It’s been a few days since I broke my head in the code.

I have a form (which gives POST on the page itself) with select fields of cities and neighborhoods. When selecting the city, the neighborhoods are listed according to the city, through the codes below.

If the user selects the city and submits, assigns the value to the $_SESSION["cidade"] then the ajax goes there and populates with the neighborhoods of the city.

Let’s say the user selects some neighborhood and submits, assigns the value to the $_SESSION["bairro"].

So far, so good! The user navigates the results, etc. when he returns to the page, he would like the fields to be populated as sessions.

I can’t do that in Ajax. When the user returns in the form, the city is there but the neighborhood is not.

Campos Selects:

<select class="form-select text-muted mb-1" id="cidadeb" name="cidadeb">
<?php
    $resCidade = $MySQLiconn->query("SELECT DISTINCT cidade FROM imoveis WHERE dataatualizacao >= 
    (DATE(NOW()) - INTERVAL ".$diasatualizados." DAY) ORDER BY cidade ASC");
    while($rowCidade=$resCidade->fetch_array()) { 
    ?>
    <option value="<?=$rowCidade['cidade'];?>" <?php if ($rowCidade['cidade'] == $cidade) echo "selected='selected'";?>><?=$rowCidade['cidade'];?></option>         
    <?} ?>
    <option value="0" <?php if ($cidade == "0") echo "selected='selected'";?>>Todas Cidades</option>
</select>
<select class="form-select text-muted mb-1" id="bairrob" name="bairrob">
    <option value="0" <?php if ($bairro == "0") echo "selected='selected'";?>>Todos Bairros</option>
</select>

Where ...

$cidade = $_SESSION["cidade"];
$bairro = $_SESSION["bairro"];

Script:

<script>
$(document).ready(function() {
  $('#cidadeb').on('change rightnow', function() {
    $.ajax({
        type: 'POST',
        url: 'lista_bairros.php',
        data: {'cidadeb': $('#cidadeb').val()},
        beforeSend: function(xhr) {
            if ($('#cidadeb').val() !== 'cidadeb') {
               $('#bairrob').html('<option value="">Carregando...</option>');
            }else{
               $('#bairrob').html('<option value="">Bairro</option>');
           }
        },
        success: function(data) {
            if ($('#cidadeb').val() !== '') {
                $('#bairrob').html('<option value="">Selecione o Bairro</option>');
                $('#bairrob').append(data);
            }
        }
    });
  }).triggerHandler("rightnow");
});
</script>

lista_bairros.php

<?php
include_once("config.php");
$postCidade = $_POST['cidadeb'];
$resBairro = $MySQLiconn->query("SELECT bairro FROM imoveis WHERE cidade='".$postCidade."' GROUP BY bairro ORDER BY bairro ASC");
while($rowBairro=$resBairro->fetch_array()) { ?>
    <option value="<?php echo $rowBairro['bairro'] ?>" <?php if ($rowBairro['bairro'] == '$bairro') echo "selected='selected'";?>><?php echo $rowBairro['bairro'] ?></option>
<?php } ?>

Every time I select a city, I put value in Sesssion, and also put into the neighborhood.

Sessions:

$_SESSION["cidade"] = "cidade que busquei";
$_SESSION["bairro"] = "bairro que busquei";

I can’t do it, it’s take the value of $_SESSION["bairro"], give Selected in select when it is listed in ajax.

I believe it is on this line (in the script), the adjustment:

$('#bairrob').html('<option value="">Selecione o Bairro</option>');

I’d be a big help without someone there to shed some light on me. I’m still learning.

Grateful

  • 1

    At what point you define which neighborhood should appear?

  • Assuming the user has already chosen the neighborhood, I put the value in $_SESSION["neighborhood"]. Whenever he comes back in fomrulário, already gives Selected in that neighborhood. Via script that I put in the post.

  • I will reformulate the reasoning, at which point in the "code" is assigned the value of the $_SESSION["bairro"]?

  • When gives the POST in fomrulário. Ex: Selected the city, from there lists the neighborhoods ... from there choose the neighborhood and Submit. Currently assigns value in Session. $_SESSION["bairro"] =$_POST["bairrob"];

  • So, but is this part in your code? Puts all the relevant part of the operation in your code

  • Okay, I’ll rephrase it better. My first post. Sorry. Gratitude for your interest in helping.

  • if you already have it in Sesssion, it is not easier during the while which generates the options check if you have the value previously selected in Session and if you have and is equal to the value of the option you are creating, also add "Selected" in the option?

  • I did it, but it didn’t happen. Because the script is in charge, it is the script that fills in. I tried <?php if ($rowBairro['bairro'] == '$bairro') echo "selected='selected'";?> but without success.

Show 3 more comments

1 answer

-1

I’ll try to help.

I believe your way of thinking in this situation is getting in the way. If you already have the city chosen in the session, it is not necessary to make 2 requests (load and ajax). You can already bring the neighborhoods in the screen load.

If you allow I will make some changes to the code.

The ideal would be to pack in functions or class but I will follow procedural as you are doing.

<select class="form-select text-muted mb-1" id="cidadeb" name="cidadeb">
<?php
    $resCidade = $MySQLiconn->query("SELECT DISTINCT cidade FROM imoveis WHERE dataatualizacao >= (DATE(NOW()) - INTERVAL ".$diasatualizados." DAY) ORDER BY cidade ASC");
    while($rowCidade=$resCidade->fetch_array()) { 
    ?>
    <option value="<?=$rowCidade['cidade'];?>" <?php if ($rowCidade['cidade'] == $cidade) echo "selected='selected'";?>><?=$rowCidade['cidade'];?></option>         
    <? } ?>
    <option value="0" <?php if ($cidade == "0") echo "selected='selected'";?>>Todas Cidades</option>
</select>

<select class="form-select text-muted mb-1" id="bairrob" name="bairrob">
    <option value="0" <?php if ($bairro == "0") echo "selected='selected'";?>>Todos Bairros</option>

<?php
    if( $cidade != "0" ){
        $resBairro = $MySQLiconn->query("SELECT bairro FROM imoveis WHERE cidade='".$cidade."' GROUP BY bairro ORDER BY bairro ASC");

    while($rowBairro=$resBairro->fetch_array()) {
?>

<option <?php if ($bairro == $rowBairro['bairro']) echo "selected='selected'";?> value="<?php echo $rowBairro['bairro']; ?>"><?php echo $rowBairro['bairro'] ?></option>

<?php
    }
}
?>

</select>

With this code you do not need to do ajax after loading the page, you have already loaded the data.

I inform you that transiting HTML the way you are doing is not ideal... you can use JSON to bring only the data and treat HTML in Js ...

I hope I’ve helped.

  • Thanks Leonardo! I tested there, but I believe, that the ajax script $('#bairrob').html('<option value="">Selecione o Bairro</option>'); you’re writing there. I understand your logic.

  • I think I’m gonna have to rephrase my question, put in more information. The user may not want any neighborhood, but always have to popular the list of neighborhoods according to the city.

  • This... put more information please... in the case I put you will only load the neighborhoods if you have selected a city... and only mark a neighborhood if you have selected the neighborhood, if you have not remained your "All Neighborhoods"

  • I understood, but as it is the ajax script that populates neighborhood, every time it is loaded, it puts there "Select the Neighborhood" even if its logic is right. It overlaps.

  • Remove . triggerHandler("rightnow") and on("change rightnow") leave only on("change")

  • I did this, hence the user when returning the page, not populate the neighborhoods. Need to redo the choice of city, for her popular neighborhoods. This triger makes her upgrade.

  • Put the code I wrote to you and remove the excerpts I said... it will work.

  • It worked Brother! You’re the man! I’ll run some more tests to confirm.

  • So, I’m so new to stackoverflow, I can’t even score on your answer. It all worked out! The code is working. Gratitude brother!

Show 4 more comments

Browser other questions tagged

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