form is submitted even if validation failed - javascript

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?

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.

Related

Form still submits after trying to call event.preventDefault()

Hi I'm trying to post my form data via ajax.
But I still want to make use of the default validation and to show the default messages from html form. So the form shows the default error messages of the form but when the form is correctly filled it does a regular form submut instead of executing the preventDefault and then my ajax method. How come it doesn't stop from submiting ? I don't understand, can anybody help me out, that would be great.
my html form:
<form id="add_address">
<div class="form-group">
<input class="form-control" type="text" name="address_address_name" required placeholder="Naam adres*" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_address" required placeholder="Straat + Nr*" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_zipcode" required placeholder="Postcode*" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_city" required placeholder="Plaats*" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_phone" placeholder="Telefoon" />
</div>
<div class="form-group">
<input class="form-control" type="text" name="address_email" required placeholder="Email*" />
</div>
<button type="submit" class="btn btn-default right">Save</button>
</form>
my javascript:
$('#add_address button').on('click',submit_form_address);
function submit_form_address(event){
form = $('#add_address');
console.log("yes here:"+ $(form)[0].checkValidity());
if( $(form)[0].checkValidity() != false){
event.preventDefault();
add_address(form);
}
}
function add_address(p_Form){
var url = '/addresses';
data = new FormData($(p_Form)[0]);
$.ajax({
url:url,
method:'POST',
data:data,
cache: false,
contentType: false,
processData: false,
success:success_add_address,
error:error
});
}
Solution for me: I now using this way and this way is working for me to use default validation of the html form and do a custom submit through ajax.
$(document).on('submit', '#add_address', function(e){
add_address($(this));
e.preventDefault();
});
if( $(form)[0].checkValidity() != false){
add_address(form);
event.preventDefault();
}
// OR
if( $(form)[0].checkValidity() != false){
add_address(form);
return false;
}

click not working

i dont understand why the click function is not being called?Is there any mistake in jquery?
<div id="chatbox">
</div>
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
jQuery.ajax({method:'post',url:'{{=URL('post')}}',
data:{'text':clientmsg,'touser'=touser},
success:function(data){
$("#usermsg").attr("value", "");
return false;
}})};
</script>
$("form").submit(function (e) {
e.preventDefault();
})
Check that for details: Stop form from submitting , Using Jquery
First you need to change your button type to button so that the form is not submitted directly when clicked.
Then you need to stop the default function of the form by using event.preventDefault() method of jquery.I am only trying to resolve the problem of page refresh here.
<form name="message" id="myForm" action="">
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="button" id="submitmsg" value="Send" />
</form>
<script type="text/javascript">
//If user submits the form
$("#myForm").submit(function(e){
e.preventDefault();
jQuery.ajax({method:'post',url:'{{=URL('post')}}',
data:$('#myForm').serialize(),//its the jquery method to serialize form data directly.
success:function(data){
$("#usermsg").attr("value", "");
}})};

Form validation is not fired in the before send call back function using jquery validation plugin

I am very new to jQuery.I have done a simple task that validation form data using jQuery validation plugin.
I have created a simple form
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/form-validate.js"></script>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" class =" requiredFieldCheck ">
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
//$("#commentForm").validate();
$(function(){
$('#commentForm').ajaxForm({
beforeSend:function(){
alert('before send');
$('#commentForm').validate();
},
success:function(){
alert("when success");
},
error:function(){
alert('when unsuccess');
}
});
$('#commentForm').ajaxSubmit();
// return false to prevent normal browser submit and page navigation
return false;
});
</script>
</body>
</html>
$.validator.addMethod("requiredFieldCheck", function (value, element) {
alert("working method requiredFieldCheck "+value);
var result;
if(value.length > 3){
result = true ;
}
else{
result = false ;
}
return result;
}, '****This content must be greater than 3 characters****');
And also in the browser console it is caught by an error Uncaught TypeError: undefined is not a function
Can anyone give me some suggestions to do form validation before sending data and essesntially using jquery validation plugin?
Thanks in Advance
you need to register adapter, for example:
jQuery.validator.unobtrusive.adapters.addSingleVal("requiredFieldCheck", "other");

submit form without redirecting

I want to submit a form to action page which is a different site however i don't want to be directed to the action page. i've tried everything but its not working for me, i've heard about ajax does the job can someone give me examples
What I want:
i want to submit a form but not be redirected
submit the form as i'm being redirected to action page i get redirected to my original page.
My code:
<form id="user-login-form" accept-charset="UTF-8" action="http://xxxxxn" method="post">
<div>
<div class="user_login_block&op=Log+in"><label for="edit-name"><span class="form-required" title="This field is required.">*</span></label>
<input type="hidden" />
<div>
<div class="user_login_block&op=Log+in"><label for="edit-name"><span class="form-required" title="This field is required.">*</span></label>
<input type="hidden" />
<input class="form-text required" id="edit-name" type="hidden" maxlength="60" name="name" size="15" value="xxxxxx2" /></div>
<div class="form-item form-type-password form-item-pass"><label for="edit-pass"></label>
<input class="form-text required" id="edit-pass" type="hidden" maxlength="60" name="pass" size="15" value="9sQ&ampzW#7PKhpqbzcCFz9jvY" />
<input type="hidden" /></div>
</div>
<input type="hidden" name="form_build_id" value="form-odWc3MFMsKIL_5vCQtPmiv0AVf0tFwBu7eP2-8" />
<input type="hidden" name="form_id" value="user_login_block" />
<div class="form-actions form-wrapper" id="edit-actions"><input class="form-submit" id="edit-submit" type="submit" name="op" value="submit" />
Check the below example:
check this link:
http://susheel61.0fees.net/ajaxtest.php
NOTE:
This is basic a example for ajax. You cant do it many other ways like using $.post, $.get etc. but $.ajax has many options like showing a loading image before the content loads.
html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ajax example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="message"></div>
<form id="myform" action="test.php">
<input type="text" name="test"/>
<input type="submit" value="submit"/>
</form>
<div id="response"></div>
<script>
$(function() {
$("#myform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
$("#message").hide();
$("#response").html(data);
}
});
});
});
</script>
</body>
</html>
If nothing works, you could redirect to a hidden iframe.
<iframe id="iframe" name="my_iframe"></iframe>
<form class="form" id="userform" target="my_iframe">
try this:
$('form').submit(function(event){
var serialObject = $(this).serialize();
//ex for post request
$.post('path_to file',{
parameters:serialObject
},function(data){
// do something after submitting
});
});
event.preventDefault()
In the php, you can redirect to back to the form by using headers:
header('Location: yourwebsite.com');
Hopefully this works for you

replace a div tag using JQuery after form submit

I am submitting a form without leaving my page through a post call Using JQuery.
After I submit I want to replace the div with the form in it with a thank you message. The problem is the message is showing before I submit and not replacing, below is my code.
$(document).ready(function() {
//When the form with id="myform" is submitted...
$("#myform").submit(function() {
//Send the serialized data to mailer.php.
$.post("mailer.php", $("#myform").serialize(),
//Take our repsonse, and replace whatever is in the "formResponse"
//div with it.
function(data) {
$("#formResponse").html(data);
}
);
return false;
});
});
and the HTML
<div data-role="content">
<form id="myform">
<div data-role="fieldcontain">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" />
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input type="email" name="email" id="email" value="" />
</div>
<div data-role="fieldcontain">
<label for="company">Company Name:</label>
<input type="text" name="company" id="company" value="" />
</div>
<input type="submit" name="submit" value="Submit" data-icon="star" data-theme="b" />
</form>
</div>
<div data-role="content" div id="formResponse">
thank you, your quote has been received and you will hear back from us shortly.
</div>
Try replacing your following code:
<div data-role="content" div id="formResponse">
for this one:
<div data-role="content" style="display:none" id="formResponse">
and then replace your following javascript function:
function(data) {
$("#formResponse").html(data);
}
for this one:
function(data) {
$("#myForm").html( $("#formResponse").html() );
}
UPDATE:
If you just want to show the result obtained from the ajax call, instead of showing the content of the #formResponse div, just remove the #formResponse div at all, and just do the following:
function(data) {
$("#myForm").html( data );
}
UPDATE 2:
You can also hide the form div and show the "thank you" div, like this:
function(data) {
$("#myForm").hide('slide', function() {$("#formResponse").show('slide');});
}
use success(data) A callback function that is executed if the request succeeds.

Categories

Resources