It is all working fine in my login-script. I get the right responses in my div (id=login_reply) and the session starts. But whenever I refresh the page, the login_reply is gone. How am I able to keep the login_reply? Thank you!
Here is the php:
if (isset($_POST['username'], $_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$check = mysql_query("SELECT * FROM `userbase` WHERE `user_name` = '$username'");
if (mysql_num_rows($check) > 0)
{
while ($row = mysql_fetch_assoc($check))
{
$user_id = $row['user_id'];
$user_name = $row['user_name'];
$user_email = $row['user_email'];
$user_password = $row['user_password'];
if ($password == $user_password)
{
$_SESSION['user_id'] = $user_id;
if (isset($_SESSION['user_id']) && $_SESSION['user_id'] != '')
echo "Welcome back '$user_name'!";
else
{
echo 'no';
}
}
else
echo 'no';
}
}
else
echo 'no';
}
Here is the jQuery
$(document).ready(function()
{
$('#login').click(function()
{
var username = $('#username').val();
var password = $('#password').val();
$.ajax(
{
type: 'POST',
url: 'php/login.php',
data: 'username=' +username + '&password=' + password,
success: function(data)
{
if (data != 'no')
{
$('#logform').slideUp(function()
{
$('#login_reply').html(data).css('color', 'white');
});
}
else
$('#login_reply').html('Invalid username or password').css('color', 'red');
}
});
return false;
});
});
The problem is that JS is just client side scripting language – it is processed only on clients browser.
If You want to login using AJAX, okay, but You have to store the values of logged in user into the session (or cookies). Then on every page load You will check whther that session or cookies are set and exists and if they does, You will write down the HTML corresponding to that of jQuery after logging in…
In other words, here is what You will do:
$_SESSION['username'](for example)$('#login_reply')$_SESSION['username']Hope this helps…
EDIT1: You also should implement the login functionality in a way that there is no JS working (disabled) on client browser so normal POST should be taken into count…
EDIT2: I also want to point out some general programming mistakes…
Here is Your code with my comments added:
And here is my rewritten code (still using mysql_*, sorry for that):