简体   繁体   中英

PHP setting cookie with button

<?
function cookie()
{
setcookie('enable',yes,time() + (60 * 1)); 
}
echo('<input type="button" onclick="cookie()" value="Gimme all the cookies!" />');
?>

I can't see any way to set cookies by a button (neither uncle google). I've tried some ways like this ↑ but neither works.

Ok, this is a simple mistake many people make when first trying out web development. It is sometimes difficult to conceptualise exactly how JavaScript and PHP interact. So, you are running a php script on the server, which generates HTML and JavaScript which is then sent off to the web browser. Once the HTML and JavaScript are loaded in the web browser, the JavaScript does not have access to the PHP functions.

So, you would have to either set cookie data by making your button call a PHP script on the server, or by performing an AJAX query.

AJAX can be a bit difficult at first, but take a look at the JQuery implementation at : http://api.jquery.com/jQuery.ajax/ .

Hope that helps.

You can't do it that way. It just wouldn't work. That Javascript function can't call the setcookie () method in PHP because there is no way it has access to it. Javascript is executed on the client side, PHP on the server side.

There are 2 ways to do this:

  • via AJAX. Could be a little more difficult at first. Preferably try method 2.
  • Make the button be inside an invisible form. When the user presses it, he's redirected to another PHP page, which sets the cookie and then redirects the user back to the original page.

Once you have succeeded with this, you can try it with AJAX, it will be easier to do and easier to understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM