For some reason, my jQuery isn’t working properly, and I can’t spot the mistake, although I may have some idea. Below is some of the code from group2.php, its for a chat application:
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
<p class="logout"><a id="exit" href="?logout=1">Exit Group</a></p>
<div style="clear:both"></div>
</div>
if(isset($_GET['logout'])){
$fp = fopen("log.html", 'w');
fwrite($fp, "");
fwrite($fp, "<div class='msgln'><i>User " . $_SESSION['name'] . " has left the chat session.</i><br></div>");
fclose($fp);
session_destroy();
header("Location: main.php"); //Redirect the user
}
?>
</div>
While below is jQuery, which is also in group2.php, where I am trying to see if the user clicked logout, then we should direct to main.php?logout=true
//If user wants to end session
$("#exit").click(function(){
var exit = confirm("Are you sure you want to end the session?");
if(exit==true){ window.location = 'main.php?logout=true';
}
});
While I am able to execute the code within if(isset($_GET['logout'])), and ask the user whether they would like to leave the room, I am unable to direct the user to main.php?logout=true after they click ‘ok’ to the question ‘Want to end session?’. Instead, the user is being directed to ?logout=1. Any suggestions on what I’m doing wrong? Thank you.
You need to prevent the default action in this case, which is to go to the
hrefin the<a>. You can do that withevent.preventDefault()orreturn false, like this:Or, if you’re never going to use it, just remove the
hrefurl, like this: