I want to use jQuery to validate fields of a Login Form, then send values by jQuery Ajax, and then check values by PHP MySQL, and finally receive JSON from PHP by that jQuery Ajax. This is a popular way, today and used by many Web Developers. I need a HTML or PHP file for Form, a JS file for jQuery validating and also Ajax, And finally a PHP file for checking values in MySQL table and make JSON.
1. In first file, create Login Form like this. I want to disable login button and enable it after validate fields:
<form id="login-form" data-ajax="false"> <label for="username">Email</label> <input id="username" name="username" type="email" autofocus> <label for="password">Password</label> <input id="password" name="password" type="password"> <a name="submit" id="login-submit" disabled>Login</a> </form>
2. In second file, write jQuery validating and also Ajax to send values to last file:
function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i); return pattern.test(emailAddress); } $('body').on('input', 'input[name = username]', function(e){ //listen to input event if (isValidEmailAddress($('#username').val()) && $('#password').val().length > 7) { //checking Email address and also password with 8 chars minimum $('#login-submit').prop('disabled', false); //enable Login button } else { $('#login-submit').prop('disabled', true); } }); $('body').on('input', 'input[name = password]', function(e){ if (isValidEmailAddress($('#username').val()) && $('#password').val().length > 7) { $('#login-submit').prop('disabled', false); //enable Login button } else { $('#login-submit').prop('disabled', true); } }); $('#username').keypress(function(e) { //listen to enter key if (isValidEmailAddress($('#username').val()) && $('#password').val().length > 7 && e.which == 13) { //if user press Enter key, I trigger click on Login button $('#login-submit').click(); } }); $('#password').keypress(function(e) { if (isValidEmailAddress($('#username').val()) && $('#password').val().length > 7 && e.which == 13) { $('#login-submit').click(); } }); $('body').on('click', '#login-submit', function(event){ //listen to click event on Login button and start Ajax $.ajax({ url: apiaddress, //address of third file like 'myapi.php' data: {action: 'login_submit', formData: $('#login-form').serialize()}, //I sent my custom var plus all of Form values type: 'POST', dataType: 'JSON', before: function() { $('#preloader').fadeIn("fast"); //Show a loader to user and say wait or something like this }, complete: function() { $('#preloader').fadeOut("fast"); }, success: function (result) { if (result['status'] == 'OK') { window.location.href = "user.php"; //if values are OK, reload page or relocate user to some page } else if (result['status'] == 'NM') { alert("Sorry! Login failed. Please check your Username and/or Password 😔 "); //Show a warning to user to correct values } }, error: function (xhr, status, error) { alert("Server Error! Please try again 😤 "); } }); });
3. In third file like myapi.php add PHP code to check values with MySQL and send to that Ajax. Remember to connect DB in a separate file like Config.php (see this post):
<?php header('Content-Type: application/json; charset=UTF-8'); include_once('config.php'); //connect to DB and more. Do not forget add $_SESSION['isuserlogged'] = "NM"; to it. if (isset($_POST['action']) && $_POST['action'] == 'login_submit') { //check if post has my custom var parse_str($_POST['formData'], $input); //parse form values $username = !empty($input['username']) ? mysqli_real_escape_string($db,$input['username']) : ''; //check values and prevent to inject code $password = !empty($input['password']) ? mysqli_real_escape_string($db,$input['password']) : ''; $password = hash('ripemd160', $password); //I add encoded password when signup users and now encode again to check it $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'"; if ($result = mysqli_query($db,$query)) { $row = mysqli_fetch_array($result); $counts = mysqli_num_rows($result); if ($counts == 1) { //match found $output = []; $output['status'] = 'OK'; $_SESSION['isuserlogged'] = $row['username'].$row['password']; echo json_encode($output); unset($_POST); } else { //not match $output = []; $output['status'] = 'NM'; echo json_encode($output); unset($_POST); } } else { echo 'MySQL Connection Error: ' . mysqli_error($db); } } ?>
4. Add some code to user special pages to check if user loggedin or not:
<?php include_once("config.php"); if(empty($_SESSION['isuserlogged']) || $_SESSION['isuserlogged'] == "NM") { //check if user loggedout session_unset(); mysqli_close($db); if(session_destroy()) { header("refresh:0;url=login.php"); //redirect user to login page again } } else { //add usual code for logged in users here } ?>
5. Do not forget add Logout button and refer user to homepage and also unset SESSIONs like above code (in If statement).