Adding simple ajax/jquery error notification to php log in

I’m using a simple PHP log in (see here)

Instead of

die ('Incorrect password');

I’d prefer an ajax option where a notification comes up on the login.php.

I’ve seen a few ajax examples using jquery to simplify but I’ve no idea how I implement into the php.

Morning stephen_

You don’t need ajax to do that - instead of calling die() with your error message, put the message into a variable and redisplay the login form. Replace your die() call with:

$login_error = "Incorrect password";

and then where you want to display your error message (above the login form, for example) you can do something like this:

<?php if (isset($login_error)): ?>
    <p class="error"><?php echo $login_error ?></p>
<?php endif; ?>

If you’re doing the authentication on a separate page from the form, you can store the message in a session variable instead and redirect back to the login form.

Copy-paste code. I don’t drink coffee! :stuck_out_tongue:



$FILE = basename(__FILE__);

// test123
$password = '7288edd0fc3ffcbe93a0cf06e3568e28521687bc';

// check if you have the POST
if (isset($_POST['password'])) {
	// just for test, wait for the server
	// check if OK
    if (sha1($_POST['password']) == $password) {
        $_SESSION['loggedIn'] = true;
			'result' => true,
			'message' => 'You did it! Redirecting in 2 seconds...',
	// if not OK, return error
    } else {
			'result' => false,
			'message' => 'You failed!',


<script src="//"></script>

// if logged in, show it!
if( isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] ) { ?>
	<p>LOGGED IN!</p>
<?php } ?>

<input type="password" id="password" /> <a href="#" id="login">LogIn</a>
<span id="error" style="color:#c00;display:none"></span>
<span id="done" style="color:#9c0;display:none"></span>

<!-- at the end of the page require a file that contains this script OR just add this -->
<script type="text/javascript">
	var ths = $(this);
	var buttonText = ths.text();
	$.post( '<?php echo $FILE ?>', { password:$('#password').val() }, function(data) {
		if( data.result == true ) {
			setTimeout(function(){ location.href='<?php echo $FILE ?>' }, 2000);
		} else {
	}, 'json');
	return false;

fretburner - thanks again I think I need you on the payroll!!!
vectorialpx - I live in Ireland - GUINNESS IT IS THEN! : )

Thanks both very much - its given me a lot to learn on as well as helping with issues I currently have…