简体   繁体   English

jQuery ajax 将变量传递给 php session,但 php session 不存储它

[英]jQuery ajax pass variable to php session, but php session not store it

I try to add class to body, and store it in php session. I use ajax to do it, but php session not store it.我尝试将 class 添加到正文中,并将其存储在 php session 中。我使用 ajax 来完成,但 php session 不存储它。 Variable is passing correct.变量传递正确。 Session is started in php function. Session开始于php function。

(function ($) {
    jQuery(document).on('click', '#wcag-button', function () {
        $('body').attr('id', 'wcag-theme');
        $('#wcag-button').hide();
        $('#wcag-button-off').show();

        var data = {
            'action': 'wcag_contrast_on',
            'bodyClass': 'wcag-theme'
        }
        $.post(Theme_Variables.ajax_url, data, function(response) {
            console.log(response);
        });
    });
})(jQuery);


add_action('wp_ajax_wcag_contrast_on', 'wcag_contrast_on');
add_action('wp_ajax_nopriv_wcag_contrast_on', 'wcag_contrast_on');

    function wcag_contrast_on() {
        session_start();
        $body_class=$_POST['bodyClass'];
        $_SESSION["usertemplate_css"] = $_POST['bodyClass'];
        //echo 'You sent ' . $body_class;
        echo ($_SESSION["usertemplate_css"]);
        $response['message']    = "Successfull Request";
        echo json_encode($response);
        wp_die();
    }

I also try to start session in header, but not working.我也尝试在 header 中启动 session,但无法正常工作。

Please try the below solution Using WordPress Init Hook请尝试以下解决方案使用 WordPress Init Hook

add_action('init', 'set_session'); 
function set_session() {
 if(!session_id()){
      session_start();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM