The problem was a missing session_start()
call in overview.php. Adding the call to the top of that file solved the issue.
Solution provided by Jay Blanchard, for more information read the comments.
Question
I am trying to process a user login without reloading the whole page. What I want to achieve is:
<div id="frame"></div>
-container, which is the main display area on the websiteWhen a user logs in successfully:
<div id="info"></div>
should fade in into the header of the site, holding information like "Logged in as: username" and a "logout" button<div id="frame"></div>
, in place of the previously displayed login formCurrently when the login via $.ajax()
is successful, 'overview.php' is being loaded into theid="frame"
container, but only static <html>
elements are displayed, not the ones that are being processed with PHP (ie. echo "Test";
). However, if i press F5 to reload the whole website, all elements are being shown properly.
I assume that is due to PHP being processed server-sided. What is the correct way to achieve what I am trying to do?
index.php:
<div id="frame" class="center">
<?php
if(!isset($_SESSION['user']))
include('./php/welcome.php');
else
include('./php/overview.php');
?>
</div>
welcome.php:
<div id="welcome">
<form id="login" class="center" action="./php/auth.php" method="post">
<div>Please login.</div>
<input id="user" class="field" type="text" name="user" value="User" /></br>
<input id="pass" class="field" type="password" name="pass" value="Pass" /></br>
<input class="button" type="submit" name="submit" value="Anmelden" />
</form>
<div id="login_error" class="error_message center">
error message
</div>
</div>
overview.php:
<div id="overview" style="background: red">
<?php
if(!isset($_SESSION['user']))
echo '<div class="error_message">error message</div>';
else
echo 'Why is this line only displayed after page refresh (F5)?';
?>
Test, this is being displayed when overview.php is loaded via ajax
</div>
index.js:
$(document).ready(function() {
//$('#frame').load('./php/welcome.php');
$("#login").submit(function(e) {
e.preventDefault();
$('#login_error:visible').hide();
$.ajax({
url: './php/auth.php',
data: $(this).serialize(),
type: 'POST',
dataType: 'json',
success: function(result) {
if(result.success == '1') {
$('#welcome').fadeOut(600);
$('#frame').load('./php/overview.php');
} else {
$('#login_error').fadeIn(600).delay(3500).fadeOut(600);
}
}
});
});
$("#logout").click(function() {
$.ajax({
url: './php/logout.php',
dataType: 'json',
success: function(result) {
if(result.logout == '1') {
$('.info, #overview').fadeOut(600);
} else {
alert('nope');
}
}
});
});
});
Solution
The problem was a missing session_start()
call in overview.php. Adding the call to the top of that file solved the issue.
Solution provided by Jay Blanchard, for more information read the comments.