Unable to set session variable in firefox and safa

2019-08-26 15:38发布

问题:

I am setting the session variable using Ajax, its working fine in chrome but not working in safari and Firefox browser

This is my Ajax method:

add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
function wdm_add_user_custom_data_options_callback()
{
    //Custom data - Sent Via AJAX post method
    $product_id = $_POST['custom_data_4']; 
    $custom_data_1 = $_POST['custom_data_1']; 
    $custom_data_2 = $_POST['custom_data_2'];
    $custom_data_3 = $_POST['custom_data_3'];


    $_SESSION['product_idd'] = $product_id;
    $_SESSION['custom_data_1'] = $custom_data_1;
    $_SESSION['product_pos'] = $custom_data_2;
    $_SESSION['product_lmm'] = $custom_data_3;
       die();
}

When I am trying to print the $_SESSION and $_POST value inside above Ajax method its working fine for all browser but when I try to assign above session variable in below function:-

function kia_add_cart_item_data( $cart_item, $product_id ){

   if(isset($_SESSION['product_pos']) && $_SESSION['product_idd']==$cart_item['product_id']){
            $posnumber=$_SESSION['product_pos'];
        }else{
            $posnumber=1;
        }
        if(isset($_SESSION['product_lmm']) && $_SESSION['product_idd']==$cart_item['product_id']){
            $lmmnumber=$_SESSION['product_lmm'];
        }else{
            $lmmnumber=1;
        }

        $array['product_id'] = $product_id;


        $cart_item['product_pos'] = $posnumber;
        $cart_item['product_lmm'] = $lmmnumber;
    return $cart_item;

}

Then I am getting else part value in case of Firefox and safari browser while it's working fine in chrome.

Please help me why I am not getting the session value in Firefox and safari.

回答1:

According to me you need to use wordpress session over here.

$wp_session = WP_Session::get_instance();

For example :

$wp_session = WP_Session::get_instance();
$wp_session ['product_idd'] = $product_id;

Above is for store the value in session and below if for how you can get the value

$wp_session = WP_Session::get_instance();
echo $wp_session ['product_idd'];

Try with this method and let me know if it is working or not for you



回答2:

Actually I was forget to pass async : false inside jQuery.ajax. Now Its working fine.

what does Async:false do in ajax

"async:false will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute"