Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery AJAX $.post to store PHP $_SESSION variables?

Help!

I'm having trouble wrestling AJAX to work for me. I have a paginated gallery with checkboxes beneath each image and I need to store the checkbox values in session variables if a user moves between the pages, so when they submit the form at any time it will include all checked values across all pages.

I'm using this jQuery code:

$(document).ready(function() {
    $(".gal-nav").click(function() {
        $.post("form-data-holder.php", $("#gallery-form").serialize());
    });
});

and the form-data-holder.php file says this:

<?php

    $_SESSION['saved'] = "true";

    foreach ($_POST as $key=>$value ) {
        if ( $key !== "submit" ) {
            $value = htmlentities(stripslashes(strip_tags($value)));
            $_SESSION[$key] = $value;
        }
    }

?>

I have two issues --

1) How do I get the checkbox values out of the serialize() function? I think there's more I have to do with something like value[] to get that array out, and then I guess store each one as a separate session variable -- unless I can store an array as a $_SESSION variable?

2) Before I even mess with any of that, I added that line $_SESSION['saved'] = "true"; to the php script and then I echo the $_SESSION keys and values on my gallery page to see if the AJAX request is even working. It's not. That $_SESSION['saved'] isn't added to the list of echoed $_SESSION variables when I return to the page.

Any help would be greatly appreciated!!

like image 721
rhodesjason Avatar asked Oct 15 '09 14:10

rhodesjason


1 Answers

You need to call session_start() in your form-data-holder.php file.

Every time you make the ajax call, you are requesting a new / fresh page from the server that isn't aware of any of the variables set in the original page.

like image 113
jeroen Avatar answered Oct 02 '22 20:10

jeroen