[Solved] How to stop form submission if email address is already available in MySQL db ? [closed]


To achieve this you will need ajax, you have two options

  1. on the username field you can have an onblur event, then call a function that will check the username in the database using the onblur event.

<input name="username" type="text" id="username" onBlur="checkAvailability()">

The onblur event occurs when an object loses focus. The onblur event
is most often used with form validation code (e.g. when the user
leaves a form field).

With this method as soon as the user finishes typing the email address and leaves the input field, the checkAvailability() function is fired up and send Asynchronous request to the server using ajax. the user will know if the username is taken even before they can submit.

  1. Collect all form data and return results when the submit button is hit without refreshing the page, (ajax as well).

Lets start with option 2 because its kinda easy.

First you will need to use prepared statements, also use php builtin password_hash and password_verify() functions for better safer passwords

lets begin, we will have a form with username field(email) only just you can see whats’s happening, then when we click the register button we start our ajax that will call the php script and return json data back to use.

index.php

<style>
.status-available{color:#2FC332;}
.status-not-available{color:#D60202;}
</style>

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
 <script type="text/javascript">
    $(document).ready(function (){

    $('#register').submit(function (event){

    var formData = {

        'username' : $('input[name=username]').val()
    };
    $.ajax({

        type : 'POST',
        data  : formData,
        url  : 'register.php',
        dataType :'json',
        encode   : true

    })
    .done(function(data){

        console.log(data); //debugging puroposes

        if(!data.success){

          if(data.errors.username){


            $('#user-availability-status').append(data.errors.username);

          }

          if(data.errors.exists){

            $('#user-availability-status').append(data.errors.exists);
            $('#submit').prop('disabled', true);
          }
        }else{

          $('#submit').prop('disabled', false);
          $('#success').append('<div class="alert alert-success">'+data.message+'</div>');
         // alert('done');
        }

    })

    .fail(function(data){

      console.log(data); //server errrors debugging puporses only
    });

    event.preventDefault();


    });

    });

</script>
<div id="frmCheckUsername">

<div id="success" class="status-available"></div>

    <form method="POST" action="register.php" id="register">
        <label>Username:</label>
        <input name="username" type="text" id="username"><span id="user-availability-status" class="status-not-available"></span><br><br>
        <button type="submit" name="submit" id="submit"> Register </button>   
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>
</form>

Register.php

<?php
require_once("dbcontroller.php");


$data   = array();
$errors = array();

if (empty($_POST['username'])) {

    $errors['username'] = 'enter username';
} else {


    $username = $_POST['username'];

    //check if username exists
    $statement = $con->prepare("SELECT email FROM users WHERE email = ? LIMIT 1");
    $statement->bind_param('s', $username);
    $statement->execute();
    $statement->store_result();
    if ($statement->num_rows == 1) {

        $errors['exists'] = 'the email ' . $username . ' already registered please login';

    }
}

if (!empty($errors)) {

    //We have errors send them back

    $data['success'] = false;
    $data['errors']  = $errors;
} else {

    //No errors insert

    $stmt = $con->prepare("INSERT INTO users (username) VALUES(?)");
    $stmt->bind_param("s", $username);
    $stmt->execute();



    $data['success'] = true;
    $data['message'] = 'user registered';

    $stmt->close();
    $con->close();
}

echo json_encode($data);



?>

dbcontroller.php is my database connection class, so you can ignore that and have your own.

This will point you to the correct direction atleast

Option 1 using the onblur event

<style>
.status-available{color:#2FC332;}
.status-not-available{color:#D60202;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function checkAvailability() {
    $("#loaderIcon").show();
    jQuery.ajax({
    url: "register.php",
    data:'username="+$("#username").val(),
    type: "POST",
    success:function(data){
        $("#user-availability-status").html(data);
        $("#loaderIcon").hide();
        $("#submit').prop('disabled', true);
    },
    error:function (){}
    });
}
</script>

<div id="frmCheckUsername">
  <label>Check Username:</label>
  <input name="username" type="text" id="username" onBlur="checkAvailability()"><span id="user-availability-status" class="status-not-available"></span>  <br><br>

  <button type="submit" name="submit" id="submit"> Register </button>  
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>

On this one as soon as the user leaves the input box the checkAvailability(); is fired up

solved How to stop form submission if email address is already available in MySQL db ? [closed]