Use $_SESSION value in function

Asked

Viewed 48 times

0

I have this Javascript function below, where I want to change the display of a link if the value of a session variable is equal to a certain value.

However, this way that I did, it’s not working, still confusing me a lot when using Javascript and PHP.

Someone could help out?

And it would be possible to do this using only PHP for the user to load the page?

<script language="JavaScript" type="text/javascript">
    document.onload=function mostraCampominha() {
      var select = <?php echo $_SESSION['aprovado']?>;
      var txt = document.getElementById("minha");
      txt.style.display = (select.value == 'sim') 
          ? "block"
          : "none";    
    }
</script>
  • What is the value of $_SESSION['approved']? For the rest of your code it seems to be an object... If it is, try using json_encode in echo and javascript you do a JSON.parse at this value: var select = JSON.parse("<? php echo json_encode($_SESSION['approved'])?>");

  • @Juniornunes The value of $_SESSION['aprovado'] would be or sim or não

1 answer

3


It’s probably the lack of quotation marks:

var select = <?php echo $_SESSION['aprovado']?>;

Should be:

var select = "<?php echo $_SESSION['aprovado']?>";

And one detail quoted by @Juniornunes is that this is wrong select.value == 'sim', the select should return a string, should look like this:

txt.style.display = select == 'sim' ? "block" : "none";

Another very important detail, this is wrong:

document.onload=function mostraCampominha() {

The correct is:

window.onload=function mostraCampominha() {

Over the quotation marks

Without the quotes probably the page is generated so after it is downloaded by the browser:

var select = sim;

Or

var select = não;

In the case of the first, Javascript will look for a variable called sim or não, as it probably does not exist he set the var select as undefined, probably your browser console should be emitting this error:

Uncaught Referenceerror: não is not defined

  • I put the quotes but still does not show link when the value is equal to yes

  • @Arthuroliveira do this var_dump($_SESSION['aprovado']); out of the tag <script>, copy the result and send me.

  • 1

    @Juniornunes thank you, that was what was missing, I edited the reply and quoted you.

  • var_dump returns this string(3) "sim" . I made these changes, but it’s not working yet

  • @Arthuroliveira the problem was the select.value == "sim" also, I adjusted the answer to this txt.style.display = select == 'sim' ? "block" : "none";

  • Even with this change still not working, I tried also using JSON as Junior said, but not for sure!

Show 2 more comments

Browser other questions tagged

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