Use $ _SESSION value in function

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 I did, it is not working, I still get confused when using Javascript and PHP.

Could someone help?

And would it be possible to do this using PHP only when the user loads 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>
    
asked by anonymous 05.12.2017 / 14:50

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 a detail quoted by @JuniorNunes is that this is wrong select.value == 'sim' , select should return a string, it should look like this:

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

Another very important detail, this is wrong:

document.onload=function mostraCampominha() {

The correct one is:

window.onload=function mostraCampominha() {

About the quotes

Without the quotation marks, the page is probably being generated after it is downloaded by the browser:

var select = sim;

Or

var select = não;

In the case of the first one, JavaScript will look for a variable named sim or não , as it probably does not exist to set var select to undefined , probably your browser console should be issuing this error:

  Uncaught ReferenceError: is not defined

    
05.12.2017 / 15:04