Set a session variable by clicking a link

Asked

Viewed 572 times

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 value of the year, so it is possible to use this variable in future database searches.

<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 you do not change page, but if it is mandatory it will not be, for me, preventing its use.

  • This dropdown is from bootstrap.

1 answer

1


Changing its structure a little 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 run 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 session change function:

change Date No.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! That way, at the click of the option of the year, so invisible to the user and without flashing the page, it will change the session of the year.

  • When I try to see the value of value he gives Undefined: var value = $(this).data("ano");&#xA; alert(value); It should be the year I selected, right?

  • Try to change $("#alterar-ano li") for $("#alterar-ano [data-ano]") and try to see the result of alert.

Browser other questions tagged

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