Best way to pass event callback from JQuery/JavaScript to php function

Hi there

I am working on a php web application.There is a function of logout.What I need is when a user click on logout a confrom box will open and when select yes then that value from cookie is removed.

I need to do some php function to execute when user select yes?

What is proper way of doing this?

so far I am using like this

$(".logoutUser").on("click",function(){
	if(confirm("Are you Sure you wish to logout?")){
	<?php
	echo "Logout is Called";
	?>
	}
	else{
		<?php 
		echo "Logout Not Called";
		?>
	}
});

That’s a debugging call that should be removed before the site goes live - some people turn it off in their browser in case you forget to remove it as there are better ways of debugging now so that call is effectively obsolete.

1 Like

you can modify the cookie through document.cookie in JavaScript.

I need to do some php function to execute when user select yes?

to run a PHP function you must make a new request to the server.

2 Likes

The proper way is to use php to delete the cookie. Do not use javascript to delete the cookie - for security reasons user session cookies should be set with the httponly attribute, meaning they will not be accessible by javascript at all - both setcookie() and session_start() functions will allow you to set httponly cookies. Therefore, your only option is to send a request to a php script on your server and this script will delete the cookie with its response headers (e.g. using setcookie() function).

Making the logout request can be done in one of several ways:

  1. Use plain html link to your logout script - no javascript necessary (however, you can create the link with javascript, of course, or use location.href='...' to load the log out script).

  2. Submit a form that targets your log out script - either with javascript’s form.submit() function or with a form button.

  3. Use javascript (ajax) to send the log out request to the server - after you receive the response use javascript to redirect the user to the page that he should see after he has logged out.

1 Like

nice explanations…Thanks to all

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.