-1

I'm using javascript to trigger my cookies and I've been told that the most reliable method to set cookies is to create them on the server side using php...

I already tested this code, but it creates the cookie on page load and I need it to be set only when the user clicks a link:

    <a href="<?php 
if (!isset($_COOKIE['my_test_cookie'])) {   
ob_start();
setcookie("my_test_cookie", "1", time()+ (86400 * 90), "/");
ob_end_flush();
}?>" onClick="javascript:HideContent('div3');">Create Cookie</a>

Is it possible to build the cookie on php and only create him onclick event?

eg: < href="#" onclick="call_the_php_function_where_we_setup_the_cookie_variables();">click here to create the cookie</a>

Community
  • 1
  • 1
bpy
  • 1,150
  • 10
  • 27

1 Answers1

0

PHP is run on the server before the page is ever seen by the client browser. There isn't any way to get PHP code to run after the page has been sent to the client.

The only solution is going to be to use AJAX in the background when the button is clicked to load a php page that does what you want.

For example, you could set up your page to run something like this when the button is clicked:

var req = new XMLHttpRequest();
req.addEventListener("load", function() {
    console.log(this.responseText);
});
req.open("GET", "http://yoursite.com/path_to_cookie_setter_page");
req.send();
Mogzol
  • 1,405
  • 1
  • 12
  • 18