Reputation: 1163
I have a form on page 1:
<form method="post" action="request-form">
<input
type="text"
id="amzQry"
name="item"
placeholder="What do you need?"
autocomplete="on"
/>
<input
id="autocomplete"
name="destination"
placeholder="where? (e.g. Buenos Aires)"
onfocus="geolocate()"
type="text"
required=""
aria-required="true"
autocomplete="off"
/>
<button type="submit" value="">
Submit
</button>
</form>
I want this information to be held in a persistent way so that even if a user subsequently logs in (to joomla in this case) the cookie data is persistent and can be called. That is why i have used cookies rather than sessions in this case. Correct me if this is not the right way of doing this.
I have some code to set and retrieve the cookie on page 2:
<?php
$itemcookie = $_POST['item'];
$detsinationcookie = $_POST['destination'];
setcookie("itemcookie", $itemcookie, strtotime('+30 days'));
setcookie("destinationcookie", $detsinationcookie, strtotime('+30 days'));
?>
But the cookie data is not appearing on the second page when it loads after form submit. If I refresh the second page the data appears in the right places, i.e. where I have called it with e.g.
<?php
echo $_COOKIE["itemcookie"];
?>
How to get the cookie data available immediately on page 2?
Upvotes: 6
Views: 8630
Reputation: 1533
You can.
All you have to do is set the cookie with a AJAX request that way the cookie is set while you are still on the page then when you refresh the page ONE time the cookie will be available to you.
Upvotes: 0
Reputation: 91742
You can't.
If you check the manual:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
^^^^^^^^^^^^^^
This means your cookies will not be available on the page / script where you set them.
You could use another variable to show the value though, for example like:
$itemcookie_value = isset($_POST['item']) ? $_POST['item'] : $_COOKIE["itemcookie"];
Upvotes: 3
Reputation: 2348
Apparently you have some output before you call setcookie() If you have some output (even one single space character) BEFORE session_start(), setcookie() or, say, header(), the browser will not recognize the cookie and they won't be available right after the script starts.
Upvotes: 0