How do i validate an email using AJAX?

Right now I have this form. I need to have it validate asynchronously using AJAX. I can’t seem to find any information on how to do this?
Here’s my HTML

<form name="myForm" method="get" onsubmit = "return(validateForm());" action=thankyou.html>
	<li>
		<label for="name">Name:</label>
			<input type="text" id="name" name="name" required/>
	</li>
	<li>
		<label>Select age:</label>
			<select id="mySelect" onchange="age()" name= "age" required>
				<option value=""></option>
				<option value="Grade 1">6</option>
				<option value="Grade 2">7</option>
				<option value="Grade 3">8</option>
				<option value="Grade 4">9</option>
				<option value="Grade 5">10</option>
				<option value="Grade 6">11</option>
			</select>	
	</li>
	<!--	<p id="selectedGrade"></p>-->
	<li>
		<label for="email">E-mail:</label>
			<input type="email" id="email" name="email" required/>
	</li>
		  <li class="button">
			<button type="submit">Submit</button>
	</li>
</form>	

Here’s my JAVASCRIPT

function validateForm() {
    var name = document.getElementById('name').value;
    var select = document.getElementById('mySelect');
    var email = document.getElementById('email').value;
    if (name == " ") {
        alert("name must be filled out");
    }
    if (select.options[select.selectedIndex].value == "Grade") {
        alert("age must be filled out");
    }

    if (email == " ") {
        alert("Email Must be  filled Out");
    }
    else {
        email.addEventListener('blur', function (event) {
            event.target.style.backgroundColor = event.target.validity.valid
                ? 'transparent'
                : '#FA8072'
        });
    }
};

First, I have to say I did a registration for an online vanilla-jas quiz and it’s not as robust as I would let us say a page with data really needs to be secure. Don’t get me wrong it’s secured pretty good, but I would not be using any passwords that I do any banking on my website as security is tough. Even the professionals get it wrong from time to time. Secondly even though you validate through javascript you should validate on the server side. I personally use PHP.

Anyways here’s my HTML Registration Form:

        <div id="registrationPage">
            <form class="registerForm" action="" method="post" autocomplete="on">

                <h1><?php echo (isset($message)) ? $message : 'Register'; ?></h1>
                <p><?php echo (isset($errPassword)) ? $errPassword : "Please fill in this form to create an account."; ?></p>
                <hr>

                <label for="username"><b>Username <span class="unavailable"> - Not Available, please choose a different one.</span></b></label>
                <input id="username" type="text" placeholder="<?php echo (isset($statusUsername) && $statusUsername) ? "Username is not available, please re-enter!" : "Enter Username"; ?>" name="data[username]" value="<?php echo (isset($data['username'])) ? $data['username'] : null; ?>" autofocus required>

                <label for="email"><?php echo (isset($errEmail)) ? $errEmail : "<b>Email</b>"; ?></label>
                <input type="email" placeholder="Enter Email" name="data[email]" value="<?php echo (isset($data['email'])) ? $data['email'] : null; ?>" required>

                <label for="psw"><b>Password <span class="recommendation">recommendation at least (8 characters long, 1 uppercasse letter, 1 number, and 1 special character)</span></b></label>
                <input id="password" type="password" placeholder="Enter Password" name="data[password]" required>

                <label for="psw-repeat"><b>Repeat Password</b></label>
                <input type="password" placeholder="Repeat Password" name="data[repeatPassword]" required>
                <hr>

                <p>By creating an account you agree to our <a href="termsPolicy.php">Terms & Privacy</a>.</p>
                <input type="submit" name="submit" value="enter" class="registerbtn">


                <div class="signin">
                    <p>Already have an account? <a href="index.php">Sign in</a>.</p>
                </div>
            </form>

Here’s my vanilla-js script:

'use strict';

const d = document;

const unavailable = d.querySelector('.unavailable');
const recommendation = d.querySelector('.recommendation');
var username = d.querySelector('#username');
var password = d.querySelector('#password');
var data = {};

/* Success function utilizing FETCH */
const duplicateUISuccess = function (status) {
    /*
     * Make <span> HTML tag visible to highlight message
     * in red.
     */
    if (status) {
        unavailable.style.display = "inline-block";
    } else {
        unavailable.style.display = "none";
    }
};

/* If Database Table fails to update data in mysql table */
const duplicateUIError = function (error) {
    console.log("Database Table did not load", error);
};


const passwordUISuccess = function(status) {
    if (status === "Strong") {
        recommendation.style.cssText = "color: green; font-size: 1.0em; font-weight: bold;";
    } else {
        recommendation.style.cssText = "color: red; font-size: 0.8em; font-weight: normal;";
    }
    recommendation.textContent = status;
};

const passwordUIError = (error) => {
  console.log("Database Table did not load", error);  
};


/*
 * Grab the status if there is an error.
 */
const handleSaveErrors = function (response) {
    if (!response.ok) {
        throw (response.status + ' : ' + response.statusText);
    }
    return response.json();
};

/*
 *  Fetch ($.get in jQuery) that basic is a simplified newer Ajax
 *  protocol (function?). 
 */
const checkRequest = (sendUrl, succeed, fail) => {
    fetch(sendUrl, {
        method: 'POST', // or 'PUT'
        body: JSON.stringify(data)

    })
            .then((response) => handleSaveErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
};

/*
 *  Grab the keystrokes
 */
const checkForDuplicate = (e) => {
    e.preventDefault();
    const sendUrl = 'checkName.php'; // Name of php file:
    data.username = username.value; // Put the keystrokes in object var:    
    
    /* 
     *  Call the checkRequest Function using sendUrl variable as the name
     *  of the php file that will be used to check against the database table.
     */ 
    
    checkRequest(sendUrl, duplicateUISuccess, duplicateUIError); 
};

/*
 * Add an Event Listener to check for username already in 
 * database table. When the person types every keyup stroke
 * is checked against the database table. 
 */

username.addEventListener('keyup', checkForDuplicate, false);

const strongPassword = (e) => {
    e.preventDefault();
    const sendUrl = 'strongPassword.php';
    data.password = password.value;
    checkRequest(sendUrl, passwordUISuccess, passwordUIError);
};

password.addEventListener('keyup', strongPassword, false);

and here’s my checkName.php script:

<?php
require_once 'assets/config/config.php';
require_once "vendor/autoload.php";
require_once 'loginFunctions.php';

use Library\Users;
use Library\Database as DB;

$db = DB::getInstance();
$pdo = $db->getConnection();

/*
 * The below must be used in order for the json to be decoded properly.
 */
$data = json_decode(file_get_contents('php://input'), true);

/*
 * Check to see if username already exists
 * in the MySQL Database Table (members).
 */
function duplicateUsername($username, $pdo) {

    try {
        $query = "SELECT 1 FROM users WHERE username = :username";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':username', $username);
        $stmt->execute();
        $row = $stmt->fetch();
        if ($row) {
            return true; // userName is in database table
        } else {
            return false; // Username isn't in database table
        }
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

$username = trim($data['username']);

$status = duplicateUsername($username, $pdo);

output($status);


/*
 * After encoding data to JSON send back to javascript using
 * these functions.
 */

function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}


function output($output) {
    http_response_code(200);
    echo json_encode($output);
}

Like I said I just use vanilla-js validation as a courtesy for user, but the real serious validation if done with php.

Here’s just a partial of validation on the php side:

    public function register($data, $status) {
        $db = DB::getInstance();
        $pdo = $db->getConnection();
        $this->pwd = password_hash($data['password'], PASSWORD_DEFAULT);
        unset($data['password']); // $this-pwd is private argument/variable:
        try {
            $this->query = 'INSERT INTO users (username, status, password, security, email, date_added) VALUES (:username, :status, :password, :security, :email, Now())';
            $this->stmt = $pdo->prepare($this->query);
            $this->result = $this->stmt->execute([':username' => $data['username'], ':status' => $status, ':password' => $this->pwd, ':security' => 'newuser', ':email' => $data['email']]);
        } catch (\PDOException $e) {
            if ($e->errorInfo[1] === 1062) {
                return false;
            } else {
                throw $e;
            }
        } catch (Exception $e) {
           /* Don't use on production server */
            echo 'Caught exception: ', $e->getMessage(), "\n";
        }

        return true;
    }

Here’s a link to it in action: https://chalkboardquiz.com/register.php

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.