set cookie on click with php -


hi want set cookie on button click have problem it
first version of code , working fine

<?php  $id = is_numeric($_get['id']) ? $_get['id'] : 1;    $cookie_name = "favoritepost";    if ( isset($_cookie[$cookie_name]) ) {      $kookie = unserialize($_cookie[$cookie_name]);  } else {      $kookie = array();  }  if ( ! in_array($id, $kookie) ) {      $kookie[] = $id;  }    setcookie($cookie_name, serialize($kookie), time() + (86400 * 30), "/"); // 86400 = 1 day  ?>  <html>

then said wanted change cookie set button click wrote code not workinf , gives me no cookie set problem. thanks

<!doctype html>  <?php  $id = is_numeric($_get['id']) ? $_get['id'] : 1;    $cookie_name = "favoritepost";    if ( isset($_cookie[$cookie_name]) ) {      $kookie = unserialize($_cookie[$cookie_name]);  } else {      $kookie = array();  }  if ( ! in_array($id, $kookie) ) {      $kookie[] = $id;  }  ?>    <button type="button" onclick="setcookie('<?php echo $cookie_name;?>', '<?php echo serialize($kookie);?>', time() + (86400 * 30), "/")">click me!</button>   <html>

you're mixing js , php, , it's deadly combination. js client-side language php sever side language.

every thing write in php executed server , write in js executed client side.


first solution use ajax calls connect php script js. call ajax function on click of button calls php script on server side save cookie.

reference: http://www.w3schools.com/php/php_ajax_php.asp


another solution perform operations on client side save/retrive cookie.

reference: http://www.w3schools.com/js/js_cookies.asp


doing on server-side preferable gives more security client side code.


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -