login.js (2129B)
1 /* Login */ 2 $(function() { 3 /* Attempt to log user in when login button clicked */ 4 $('#login_form').on('submit', function(e) { 5 /* Don't change page, just in case login fails */ 6 e.preventDefault(); 7 8 /* Pass username and password to php */ 9 $.post('/php/login.php', { user: $('#user').val(), pwd: $('#pwd').val() }, 10 function(data) { 11 /* Username not found in database */ 12 if (data == 'User not found') 13 alert('User not found'); 14 /* Username found BUT password incorrect */ 15 else if (data == 'Password incorrect') 16 alert('Password incorrect'); 17 /* Credentials correct, so log in user */ 18 else 19 window.location.replace('/home.php'); 20 } 21 ); 22 }) 23 }); 24 25 /* Using jquery's validation plugin for input validation 26 * https://jqueryvalidation.org/ 27 */ 28 function validate_form(id) { 29 /* Store state in variable */ 30 var valid = $('#login_form').validate({ 31 rules: { 32 /* Username is required */ 33 user: 'required', 34 /* Password is required with a minimum of three characters */ 35 pwd: { 36 required: true, 37 minlength: 3 38 }, 39 } 40 }).checkForm(); 41 42 /* Enable or disable login button based on validation state */ 43 if (valid) { 44 $('#login').prop('disabled', false); 45 $('#login').removeClass('isDisabled'); 46 } else { 47 $('#login').prop('disabled', 'disabled'); 48 $('#login').addClass('isDisabled'); 49 } 50 } 51 52 /* Toggle password */ 53 function toggle() { 54 var field = document.getElementById('pwd'); 55 56 if (field.type === 'password') field.type = 'text'; 57 else field.type = 'password'; 58 } 59 60 /* Login button disabled when page first loaded */ 61 $('#login_form').on('blur keyup change', 'input', function(event) { 62 validate_form('#login_form'); 63 }); 64 validate_form('#login_form');