Reputation: 1
I try to check if an email exists before allowing to submit the form.
if the email exists, I get the alert which I added to test the form, but it still submits the form and moves to "login.asp". I also added "event.preventDefault();" to try and stop it, but still it happens Here is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://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('User_RegisterCheck.asp', {
'email': emailVal
}, function(data) {
if (data == 'exist') {
alert('exits');
return false;
event.preventDefault();
} else $('#FormRegID').submit();
});
});
});
</script>
</head>
<body>
<form method="post" id="FormRegID" name="FormRegID" action="login.asp">
<div class="form-group ">
<label for="email" class="control-label">email</label>
<input type="email" class="form-control w-75" id="email" name="email" placeholder="email" required>
</div>
<input type="image" name="Submit" src="/images/button_login-register.png" border="0" alt="Submit" id="Submit" style="width: 209px;" />
</div>
</form>
</body>
</html>
How can I validate the email?
Upvotes: 0
Views: 128
Reputation: 337560
The issue is because you stop the submission too late; you're doing it in the AJAX request which is asynchronous. The form has already been sent by the time that occurs.
To fix this call preventDefault()
on the event, regardless of the state of the AJAX request. Then you can make the request and if the validation passes you can submit the form
element (note: not the jQuery object containing the form) and allow the data to be sent to the server. Try this:
<form method="post" id="FormRegID" name="FormRegID" action="login.asp">
<div class="form-group ">
<label for="email" class="control-label">email</label>
<input type="email" class="form-control w-75" id="email" name="email" placeholder="email" required>
</div>
<input type="image" name="Submit" src="/images/button_login-register.png" border="0" alt="Submit" id="Submit" style="width: 209px;" />
</div>
</form>
jQuery(function($) {
$('#FormRegID').on('submit', function(e) {
e.preventDefault();
var emailVal = $('#email').val();
$.post('User_RegisterCheck.asp', {
'email': emailVal
}, function(data) {
if (data.trim() !== 'exist')
this.submit();
});
});
});
Note that this hooks to the submit
event of the form
, not the click
of the button
.
I would also suggest you return a boolean value in a formal data structure from your AJAX call, such as JSON, instead of plaintext. This is because whitespace can cause problems with the latter being interpreted correctly.
Upvotes: 1