简体   繁体   中英

jQuery and ajax to set session variable in PHP

I'm using a session variable in PHP to manage the current language in a multi-language site. To achieve what I want I'm using a flag icon that when clicked (jQuery) it tells lang_json.php to switch the session variable to the new language.

I'm not getting errors on the jQuery side:

var sendData =  'en';  

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "lang_json.php",
    data: ({newLang: sendData}), 
    dataType: "json",
    success: function (msg) {
      alert('Success');
    },
    error: function (err){
      alert('Error');
    }
});

But the PHP file is not setting the session variable:

lang_json.php:

<?php

// Session variables
session_name('aklogin'); // Starting the session
session_start();

if( isset($_POST['newLang']) ){
    $_SESSION['current_lan'] = $_POST['newLang'];
}else{
    $_SESSION['current_lan'] = "Not Posting";
}

?>

The session variable is returning "Not Posting".

You claim you are sending the server JSON, but:

  • You aren't
  • The PHP isn't set up to receive JSON

Remove contentType: "application/json; charset=utf-8", , then jQuery will set the correct content-type and PHP will populate $_POST .

I kept playing with the jQuery side and this is what worked:

var sendData =  'en'; 

$.ajax({
    type: 'POST',
    url: 'app/pro/pro_lang_session_json.php',
    data: {'newLang': sendData}, 
    success: function (msg) {
        alert(sendData);
    },
    error: function (err){
        alert('Error');
    }
});

The session variable sets to 'en' with this code.

Thank you for your help! @DelightedDOD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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