I am creating a multi-step form with Ajax and would like to change text displayed based on the value of a form field. I thought that a good way to do this would be with a session variable. How do I tell the session to update with the new field value? Currently, the session only seems to store the initial value, but not any updates to it. So if a user enters "John" as the first name and then later goes back and changes it to "Frank," "John" is the name stored.
if (!isset($_SESSION)) {
session_start();
$_SESSION['formStarted'] = true;
$_SESSION['timestamp'] = date("M d Y H:i:s");
$_SESSION[$key] = $value;
<p>Your name begins with the letter <?php if ($_SESSION['name'] =='Frank')
{echo 'F';}?><p>
jQuery:
$("#form").validate({
//...
submitHandler: function(form) {
//...
$(form).ajaxSubmit({
type: "POST",
data: {
name : $('#name').val(),
//...
},
dataType: 'json',
url: '../ajaxtest.php',
error: function() {alert("There was an error processing this page.");},
success:
function(data) {
$('#output1').html(data.message.join(' ')).show(500);
$('#ouput1').append(data);
//...
ajaxtest.php:
session_start();
$expected = array(
'name'=>'string',
//...
);
//...
$return['message']=array();
if(!empty($_POST['name'])){
$return['message'][] = '' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
}
//...
echo json_encode($return);
If you want to create a persistent session between pages, you need to call session_start
at the start of every script that the session should apply to, not just the first one.
The PHP docs for session_start
say that the function will cause the session to persist if it already exists.
Thats how $_SESSION should work. Because same variable might be in use at different pages, and under processing and so changing values will be unacceptable.
In your case, you are trying to update $_SESSION['name'] and need to keep all other session values intact. The possible solution is
<?php
session_start();
unset($_SESSION['name']);//remove $_SESSION['name']
session_regenerate_id();//Copies all other session variables on to new id
$_SESSION["name"] = $newValue;//Create new session variable 'name'.
session_write_close();
?>
You can update the $_SESSION
like you update a simple variable. The $_SESSION
is a global var and you can access it after session_start()
declaration.
It's not required to unset
the session
when you want to change because you are working at the same memory
address.
For example:
index.php
<?php
session_start();
$_SESSION['key'] = 'firstValue';
anotherpage.php
<?php
session_start();
session_regenerate_id() // that's not required
$_SESSION['key'] = 'newValue';
checkpage.php
<?php
session_start();
echo $_SESSIOn['key'];
Navigation
index.php -> anotherpage.php -> checkpage.php // output 'newValue'