I am attempting to validate an email address if it already exists in a table, but this isn't working.
Here's my code:
<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">
$('#Submit').click(function() {
var emailVal = $('#email').val(); // assuming this is a input text field
$.post('checkemail.php', {'email' : emailVal}, function(data) {
alert(data);
});
});
</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="submit" name="Submit" id="Submit" value="Submit" />
</p>
</form>
</body></html>
When the Submit button is clicked, it should validate first using the jQuery and call the checkemail.php file as shown below:
<?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 "The email already exists.";
}
?>
However, when I click the submit button it goes to view.php instead of checkemail.php. Before it redirects to view.php, it should check first if the email already exists or not. If the email already exists, then it should not redirect to view.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';
?>
Best practice for these kind of stuff is to use Jquery remote validate method.
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: "check-email.php"
}
},
messages:{
email:'Email address exists.'
}
});
In PHP file, you can do what @Sachyn has mentioned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With