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:


<?php

session_start();

// GET CURRENT FILE, FOR THIS TEST ONLY
$FILE = basename(__FILE__);

// test123
$password = '7288edd0fc3ffcbe93a0cf06e3568e28521687bc';

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

?>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<?php
// 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">
$('#login').click(function(){
	var ths = $(this);
	$('#error').html('').hide();
	$('#done').html('').hide();
	
	var buttonText = ths.text();
	ths.text('Wait...');
	$.post( '<?php echo $FILE ?>', { password:$('#password').val() }, function(data) {
		ths.text(buttonText);
		if( data.result == true ) {
			$('#done').show().html(data.message);
			setTimeout(function(){ location.href='<?php echo $FILE ?>' }, 2000);
		} else {
			$('#error').show().html(data.message);
		}
	}, 'json');
	return false;
});
</script>

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…