Define a session variable by clicking on a link

1

I have a dropdown list, which allows you to choose the year that will be used in the database search. I would like the user to select one of these dates, set a session variable with the year value, and thus be able to use this variable in future searches to the database.

<li class="dropdown" id="teste">
    <a style="color:white;"href="#" class="dropdown-toggle" data-toggle="dropdown"
       role="button" aria-haspopup="true" aria-expanded="false">
       2016 <span class="caret"></span></a>
  <ul class="dropdown-menu">
    <li><a href="#">2015</a></li>
    <li><a href="#">2017</a></li>
  </ul>
</li>

If possible do not change page, but if it is mandatory will not, for me, prevent its use.

    
asked by anonymous 22.01.2017 / 22:57

1 answer

1

Changing your structure a bit to:

<li class="dropdown">
    <a style="color:white;"href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
    2016 <span class="caret"></span></a>
    <ul id="alterar-ano" class="dropdown-menu">
        <li><a data-ano="2015" href="#">2015</a></li>
        <li><a data-ano="2016" href="#">2017</a></li>
    </ul>
</li>

A script in javascript using jQuery to execute the session invisibly.

<script>
    $("#alterar-ano li").click(function(event){
        // pega o ano selecionado pelo evento do clique
        var value = $(this).data("ano");
        // executa uma função em ajax direcionando para outra página em PHP que irá trocar a sessão
        var url = "alterarSessaoDoAno.php";
        $.post(url, {ano: value}, 
        function(retorno){
            // ...
        });
        event.preventDefault();
    });

</script>

External file with function to change session:

changeAssessment.php

<?php
    session_start();
    // aqui você personaliza o nome da sessão de acordo com o que já tem (se tiver).
    $_SESSION['ano'] = $_POST['ano'];
    header('Content-Type: application/json');
    echo json_encode(array('status' => true));
?>

That's it! This way, in the click of the year option, invisibly to the user and without blinking the page, it will change the session of the year.

    
22.01.2017 / 23:24