Reputation: 103
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".
Upvotes: 3
Views: 6714
Reputation: 944320
You claim you are sending the server JSON, but:
Remove contentType: "application/json; charset=utf-8",
, then jQuery will set the correct content-type and PHP will populate $_POST
.
Upvotes: 2
Reputation: 103
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
Upvotes: 0