如何使用jQuery AJAX $ .post存储PHP $ _SESSION变量?

时间:2022-09-20 11:14:11

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.

我无法摔跤AJAX为我工作。我有一个分页库,每个图像下面都有复选框,如果用户在页面之间移动,我需要将复选框值存储在会话变量中,因此当他们随时提交表单时,它将包括所有页面中的所有选中值。

I'm using this jQuery code:

我正在使用这个jQuery代码:

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

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

和form-data-holder.php文件说:

<?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?

1)如何从serialize()函数中获取复选框值?我认为我需要做更多的事情,比如value []来取出那个数组,然后我想把每个存储作为一个单独的会话变量 - 除非我可以将数组存储为$ _SESSION变量?

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.

2)在我搞乱之前,我添加了行$ _SESSION ['saved'] =“true”;到PHP脚本,然后我回应我的画廊页面上的$ _SESSION键和值,看看AJAX请求是否正常工作。不是。当我返回页面时,$ _SESSION ['saved']没有添加到echoed $ _SESSION变量列表中。

Any help would be greatly appreciated!!

任何帮助将不胜感激!!

1 个解决方案

#1


6  

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

您需要在form-data-holder.php文件中调用session_start()。

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.

每次进行ajax调用时,都会从服务器请求一个新的/新页面,该页面不知道原始页面中设置的任何变量。

#1


6  

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

您需要在form-data-holder.php文件中调用session_start()。

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.

每次进行ajax调用时,都会从服务器请求一个新的/新页面,该页面不知道原始页面中设置的任何变量。