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);
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With