0

i have made a function destroy() that is being called onclick event of logout button. But the problem is server side code in that function being always called on page load whether the logout button being clicked or not. All i want to do is to set a value for session varaible lastVisit onclick event of logout button. Kindly let me know what is an appropriate way to do it thanks,

              function destroy()
                {
                <?php $_SESSION['lastVisit'] = "logout"; ?>
                alert('hi');

                }
user2304394
  • 323
  • 2
  • 10
  • 24

2 Answers2

2

You are mixing php code with javascript code they dont work together like that you will need to do an ajax call and this is made easy since you are using jQuery.

Javascript

jQuery(document).ready(function() {
   jQuery("#LogoutButtonID").click(destroy());
});
function destroy() {
   jQuery.ajax({
      "url":"http://www.example.com/someScriptToLogout.php",
      "success":function() {
         alert("i logged out");
      }
   });
}

and in someScriptToLogout.php

<?php
session_start();
$_SESSION['lastVisit'] = "logout";
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
1

Why not go the Ajax way?

PHP:

if(isset($_POST['endSession'])){
destroy();

echo 'Hi';
}

function destroy(){
  $_SESSION['lastVisit'] = "logout"; 
                }

javascript:

$.post('logOut.php',{endSession:'yes'},function(hi){

alert(hi)

})

That for sure will do what you want

Please note: This solution will assume that you have jQuery in your page and that your php codes are in a page named logOut.php

ErickBest
  • 4,586
  • 5
  • 31
  • 43