How to Check Email Already Exists After Form Submission

How to check email already exists after form submission

Maybe you could try something like this:

So I assume you have an <input> field for the email.

First, add enteredEmail to your state.

this.state = {
email: [],
interest: "",
success: false,
error: false,
errorMessage: "",
loading: false,
enteredEmail: "",
};

After, add another handler to the Form to update the enteredEmail:

handleInputChange = (e) => {
this.setState({enteredEmail: e.target.value})
};

Pass the handleInputChange to your input as something like

onChange={props.handleInputChange}

Then, inside your handleSubmit you could try to see if this email exists in the email array.

handleSubmit(e) {
e.preventDefault();
const { email, interest, enteredEmail } = this.state;
//Email already registered
const filterEmail = email.filter(x => x === enteredEmail);
if (filterEmail) {
this.setState({
error: true,
errorMessage: "Email already subscribed"
});
}

Check if email address already exists in the database using jQuery and PHP

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //newly added
$('#Submit').click(function() {alert('in');
var emailVal = $('#email').val(); // assuming this is a input text field
$.post('checkemail.php', {'email' : emailVal}, function(data) {
if(data=='exist') return false;
else $('#form1').submit();
});
});});
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="view.php">
<p>
<input type="text" name="email" id="email" />
</p>
<p>
<input type="button" name="Submit" id="Submit" value="Submit" />
</p>
</form>
</body>
</html>

php Code

<?php
include("../includes/db.php");

$sql = "SELECT email FROM lf_clients WHERE email = " .$_POST['email'];
$select = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($select);

if (mysqli_num_rows > 0) {
echo "exist";
}else echo 'notexist';
?>

Check if email already exists and FILTER_VALIDATE_EMAIL in same function

Your Update query looks like it is in the wrong place. According to your code, if the posted email value is not set, you are updating the DB. I am guessing that is not what you want to do. The other problem I see is you are only passing the $sql variable to the function. The posted value will never be set.

//initalize flags
$flag1 = "no";
$flag2 = "no";
if( isset($_POST['email'])){
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo "Invalid e-mail, please try a different.";
exit;
}else{
//use flag here for for last if
$flag1 = "yes";
}
$check_email = $sql->query("SELECT email FROM auth WHERE email='$newemail'");
if ($check_email-> num_rows) {
echo "E-mail is already in use.";
exit;
}else{
//set 2nd flag here
$flag2 = "yes";
}

if( $flag1 == "yes" && $flag2 == "yes"){
//update query for new email here
}
}else{
//do something when no email is posted
}

MySQL - Check if username already exists before submitting the form

If you want to check before submitting the form you can go for ajax only.check after click the submit button this will work you can try this out.

<?php
$servername = "xxxxxxxxx";
$username = "xxxxxxxxxx";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if(isset($_POST['submit'])) {
$username=$_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];

//Query statement with placeholder
$query = "SELECT fname
FROM person
WHERE fname = '$username'";

// Execute it
try {
$stmt = $conn->prepare($query);
//for you no need to pass parameter inside execute statement
$result = $stmt->execute();
//After executing the query store the result like below
$stmt->store_result();
} catch(PDOException $ex) {
echo $ex->getMessage();
}

//Now Check for the row count
//you have to check numrows >0 like this
if($stmt->num_rows>0) {
echo "Account Exists";
die;
} else {
$sql = "INSERT INTO person(username,email,password) VALUES ('$username','$email','$password')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>

Form is getting submitted even if email exist in database...How to clear email field and ask user to enter non existing email ID

This is happening because you're not preventing the default behaviour of the browser by using event.preventDefault() or return with either false or true accordingly.

function [...](e) {
e.preventDefault();
[...]
}

You should also have a syntax error because of the random return false; you have in you AJAX code.

Change,

success:function(data) {   
if(data) {
alert('Email Already Exists');

} else {
alert('Email Available');
}
},
return false; <---- Here...

to,

success:function(data) {   
if(data) {
alert('Email Already Exists');

} else {
alert('Email Available');
}

return false; <---- Here...
},

How to stop form submission if email address is already available in MySQL db ?

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



Related Topics



Leave a reply



Submit