I am trying to access the session variables through a Jquery Ajax call. However, the jquery response keeps throwing the "Unexpected token < in JSON" error.
Here is my Jquery code -
$( document ).ready(function() {
$.ajax({
url: "mysession.php",
dataType: "json",
success: function(response){
if(response.userid == ""){
alert(response.userid);
$("#WelcomeMsg").html("");
}else{
$("#WelcomeMsg").html("Welcome<br>"+response.username);
}
},
error : function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status+", " + jqXHR.statusText+", "+textStatus+", "+errorThrown);
}
});
});
On the PHP side my code includes the following -
header("Content-Type: application/json");
// Start the session
session_start();
if(isset($_SESSION["user"]))
{
$userid = $_SESSION["user"];
$username = $_SESSION["name"];
$studentlog = array("userid" => $userid , "username" => $username, "Err"=>"");
echo json_encode($studentlog);
}else
{
$userid = "";
$username = "";
$studentlog = array("userid" => $userid , "username" => $username, "Err"=>"");
echo json_encode($studentlog);
}
Can somebody please suggest what wrong I am doing while doing the json encoding
Edit: A little more background to the problem. As you can understand I am basically new to PHP and using session variables for the first time. Earlier I had written a login script with similar code (but did not use session variables), to get username from the database and perform user validation. The Jquery Ajax calls were absolutely similar and the data was being returned by json_encode. The code seemed to have been working fine.
But now after I have started using session variables to get the user login status there seems to be a problem. In fact the same login script is also throwing an error. (I have provided the other php script over here considering the length of the login script)
One more observation, if I simply comment out session_start() in the login script, everything once again works fine. Hope I have explained myself fine.