isset / empty php session(if else语句)给出未定义的索引
I've been wanting to create a javascript function that changes the PHP session onclick. Changing the session is working to only a certain extent. When I put an if else statement using isset, it gives an error of undefined index for the second condition block (else). Searched everywhere, but could not find any leads at all. Do help me. Thanks! Here's my code.
Javascript
function changeLangToSpanish(){
var lang = "spanish";
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Reload the page
window.location.reload();
}
}
xmlhttp.open("POST","set_session.php?lang=" + lang,true);
xmlhttp.send();
}
function changeLangToEng(){
var lang = "english";
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Reload the page
window.location.reload();
}
}
xmlhttp.open("POST","set_session.php?lang=" + lang,true);
xmlhttp.send();
}
PHP (set_session.php)
<?php
if(!isset($_SESSION)){
session_start();
}
if(!isset($_SESSION['lang'])){
$_SESSION['lang'] = "english";
}
else if(isset($_SESSION['lang'])){
$_SESSION['lang'] = $_REQUEST['lang'];
}
?>
HTML (for testing purposes)
<html>
<head>
<?php
include "header.php";
include "set_session.php";
?>
</head>
<body>
<button id = "lol" onclick = "changeLangToSpanish()">lol</button>
<button id = "lol" onclick = "changeLangToEng()">loll</button>
<span id = "lols"></span>
<?php
if(isset($_SESSION['lang'])){
echo '<script>
document.getElementById("lols").innerHTML = "'.$_SESSION["lang"].'";
</script>';
}
?>
</body>
</html>
So, basically there's a HTML that shows the session in a span. The change of session is caused by the click of the 2 buttons, where the left button sets the session to "spanish" and the right to "english". It can be seen that the span shows "english" due to the initialization of the session, but when I click either of the buttons, an undefined index error pops up, indicating error in the (else) block of code. Using empty instead of isset does not solve it as well. And I'm unable to toggle between the sessions. Hope that I could get a solution. Thanks!
It looks like there is a potential bug in:
else if(isset($_SESSION['lang'])){
$_SESSION['lang'] = $_REQUEST['lang'];
In particular, this code does not check whether $_REQUEST['lang'] is actually set. Maybe you mean to check that instead of checking $_SESSION['lang'] (whose value is being overwritten here)?