PelHout
PelHout

Reputation: 83

Save submitted form values as cookie

Right now I am storing session variables with jQuery like:

$("form#sessie_datum").change(function() {
 var str = $("form#sessie_datum").serialize();
 $.ajax({
           type: 'POST',
           url: 'http://URL.com/datum.php',
           data: $("form#sessie_datum").serialize(),
           dataType: 'text',
           success: function() {
           alert('Variables has been stored in the session');
           },
 });
 return false;
});

In my datum.php file I get the submitted values by name, this is my form:

<form id="sessie_datum">
<input type="text" class="aantal_alpincenter" name="personen_aantal" value="">
<input type="text" id="datepicker2" placeholder="Click to choose a date" name="wapbk_hidden_date" value="">
<div id="datepicker"></div>
</form>

datum.php beneath here

<?php

session_start();
$_SESSION["chosen_date"] = $_POST['wapbk_hidden_date'];
$_SESSION["personen"] = $_POST['personen_aantal'];

?>

In every php file I can get the session variables like:

session_start();
$date = htmlentities($_SESSION["chosen_date"]);

Instead of using session_start(); I want to use cookies so I can prevent a conflict with my caching plugin and let the variables been stored on the user their computer for 1 day for example. Anyone knows how to do this with cookies?

Upvotes: 1

Views: 1656

Answers (1)

makstech
makstech

Reputation: 68

You can save cookies with setcookie() function.

Simply saving all POST data to cookies with PHP would be something like that:

<?php 
// Check if request method is post
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  foreach ($_POST as $key => $value) {
    // If you wanna modify key text, you may do so like this:
    switch ($key) {
      case 'wapbk_hidden_date':
        $cookie_key = 'chosen_date';
        break;

      case 'personen_aantal':
        $cookie_key = 'personen';
        break;

      default:
        $cookie_key = $key;
        break;
    }

    // Saves cookie for 1 day on this domain
    setcookie($cookie_key, $value, time()+3600*24, "/");
  }
}

And then, when you want to use your cookie, get it with global variable $_COOKIE:

$date = htmlentities($_COOKIE['chosen_date']);

Upvotes: 1

Related Questions