-3

i dont know what to say but, i have a banner with a session variable, if that session variable is set and have a value 1 then i have displayed that banner. i also have a button to hide that banner and i have called a javascript function onclick that button.

so i have created a simple javascript function and added some php code with php tag to unset the session variable. I can also use ajax to unset the session variable. but i was thinking to do that with that function why to do ajax call.

i have some code:

<?php if($_SESSION['SHOW_BANNER']==1){ ?>

     <div id="banner">Banner goes here</div>
     <button  onclick="hideit()">Hide</button>

<?php } ?>

Here is jquery function:

<script>
   function hideit()
   {   
       <?php unset($_SESSION['SHOW_BANNER']); ?> 
       $("#banner").hide();
   }
</script>

Each time when i reload the page, the session variable is unset. Any Help..

Shail Paras
  • 1,125
  • 1
  • 14
  • 34
  • 1
    Of course it'll be unset as PHP code is parsed by the server each time the page is reloaded. There is no way to prevent that. – D4V1D Apr 01 '14 at 12:53
  • hi Quentin.. i think you need to read my question and you given reference once again.. they both are different. In my case php code is executing but in referenced question php code is not working.. – Shail Paras Apr 01 '14 at 13:02
  • i think i should use ajax.. thanks Steve – Shail Paras Apr 01 '14 at 13:02

1 Answers1

1

You can't execute PHP code directly from JavaScript. PHP code is executed when page is rendering on server side, and if you have syntax like:

function hideit()
{   
   <?php unset($_SESSION['SHOW_BANNER']); ?> 
   $("#banner").hide();
}

It executes every time unset when page is loaded and result of this code is returned to JavaScript. Only way to unset session variable is to execute code on server side, you can do this with simply ajax call.

function hideit()
{ 
    $("#banner").hide();
    $.get("hideBanner.php");
}

And in hideBanner.php just execute

<?php unset($_SESSION['SHOW_BANNER']); ?>
Kamil
  • 196
  • 3