Reputation:
When I click on Logout link, my logout.php file is called which logs me out.
<a href=logout.php>Logout</a>
How can I call following javascript function before calling the logout.php file on the click of the Logout link.
Javascript function
function callMeBeforeLogout()
{
alert("Do you really want to logout?");
}
Upvotes: 0
Views: 1677
Reputation: 135197
I prefer an unobtrusive approach
<a href="/logout" id="logout-link">logout</a>
Then add the script
<script>
var logoutLink = document.getElementById("logout-link");
logoutLink.addEventListener("click", function(event) {
if (confirm("Do you really want to logout?")) return;
event.preventDefault();
});
</script>
If the user clicks "OK", they just follow the href
provided in the original link (/logout
)
If the user clicks "Cancel", the confirmation dialog will go away, and nothing happens.
If the user has JavaScript disabled, the link will work, just without confirmation dialog.
Upvotes: 5
Reputation: 126
try add onclick event
<a href="javascript:void(0);" onclick="callMeBeforeLogout();">Logout</a>
function callMeBeforeLogout() {
alert('hi i m here');
}
if you want to redirect use window.location
or window.location.href
Upvotes: 3
Reputation: 28763
Try like
<a href="javascript:;" onclick="callMeBeforeLogout();">Logout</a>
And in your function you have to write like
function callMeBeforeLogout()
{
var cnfrm = confirm("Do you really want to logout?");
if(cnfrm) {
// here redirect to `logout.php`
window.location.href = 'logout.php';
}
}
Upvotes: 1