CL. L CL. L - 2 months ago 6
Ajax Question

Cannot Keep Ajax Preserved Session Variables

I am trying to write code to bring session variables from one php to another without refreshing. I tried to follow the example I found on web as below. It seems to bring the value successfully when loading the ajax page. However, the session variable created seems unable to be preserved even I use the

session_start()
command. Instead of loading the data, it shows the following error message:


Notice: Undefined index: numSum in C:\xampp\htdocs\test\update.php on line 5


I'd appreciate it if anyone can advise what to do with the code in order to get it right.

index.php

<html>
<?php
session_start();
?>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
j_TOC = [1,2,3,4,5];

$.ajax({
method: "POST",
url: "update.php",
data: { numSum: j_TOC}
})

.done(function( msg ) {
alert( "Data Saved: " + msg );
});

</script>
</html>


update.php

<html>
<?php
session_start();
session_save_path('/session_data/');
$_SESSION['numSum1'] = $_POST['numSum'];

?>
<script type="text/javascript">
function atest() {

var id_toc = <?php echo json_encode($_SESSION['numSum1']); ?>;
window.alert(id_toc);
{

</script>
<input type="button" id="clickme" onclick="atest()" value="update session"></>
</html>

Answer

There are few issues with your code, such as:

  • Normal code flow: When you first visit index.php, it will trigger the AJAX request, and will subsequently set the session variable; so that when you visit update.php page, you'll get the desired result.
  • Your code flow: Having said the above point, if you directly visit the update.php page without visiting index.php in the first place, you'll get this error,

    Notice: Undefined index: numSum in ...

    And that's because $_POST['numSum'] is not set, in fact, the entire superglobal $_POST array is empty.

    So the solution is this,

    Wrap this statement $_SESSION['numSum1'] = $_POST['numSum']; inside an if block, like this:

    if(!isset($_SESSION['numSum1']) || empty($_SESSION['numSum1'])){
        $_SESSION['numSum1'] = isset($_POST['numSum']) ? $_POST['numSum'] : array();
    }
    
  • There's also a small syntax error in your code,

    function atest() {
    
        var id_toc = <?php echo json_encode($_SESSION['numSum1']); ?>;
        window.alert(id_toc);
    {   <============ See here, it should be }
    

    You forgot to add a closing parentheses }

  • Finally, from the documentation,

    ... Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.

Comments