where to use preventDefault(); in jquery to stop submit form data - javascript

I am trying to submit a form data to php using jquery. I dont want to submit it by default. code is working fine. I dont know where to use event.preventDefault();
below is my jquery code
<script>
$(function () {
$("#submit").click(function () {
var password = $("#password").val();
var confirmPassword = $("#confirm_password").val();
var dataString='password='+ password + 'confirmPassword='+ confirmPassword;
if (password != confirmPassword) {
alert("Passwords and Confirm Password Should match.");
return false;
}
else{
$.ajax({
type: "POST",
url: "update-password.php",
data: dataString,
success: function(result){
alert(result)
}
});
}
});
});
</script>

Don't use click events to control form submission. It is bypassed by keyboard form submission! Always use the submit event.
As you are submitting the form via Ajax you can stop the submit immediately with e.preventDefault()
e.g.
$(function() {
$("form").submit(function(e) {
e.preventDefault();
var password = $("#password").val();
var confirmPassword = $("#confirm_password").val();
var dataString = 'password=' + password + 'confirmPassword=' + confirmPassword;
if (password != confirmPassword) {
alert("Passwords and Confirm Password Should match.");
} else {
$.ajax({
type: "POST",
url: "update-password.php",
data: dataString,
success: function(result) {
alert(result)
}
});
}
});
});
Note: as you are not doing anything special with the submit, you might as well not use Ajax unless you needed to. Just conditionally return true or false.
Returning false is the same as e.preventDefault() and e.stopPropagation().
e.g.
$(function() {
$("form").submit(function() {
var password = $("#password").val();
var confirmPassword = $("#confirm_password").val();
var dataString = 'password=' + password + 'confirmPassword=' + confirmPassword;
if (password != confirmPassword) {
alert("Passwords and Confirm Password Should match.");
return false
}
});
});
General advice: Don't use alert for interaction with the user. Show validation messages on the page instead.

Related

How to prevent form submit?

I have a login form and a captcha field. I need a javascript source to check this captcha input then send post data to action but my code seems to be wrong, the e.preventDefault function doesn't work because captcha field true or false post data's still sent. please help.
This my javascript Function:
$(document).ready(function () {
$("#signupform").submit(function (event) {
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
event.preventDefault();
//Form post data still sent?
}
}
});
}
else alert("Captcha not null");
});
});
You need to move event.preventDefault(); up so it comes before the ajax call.
Use $("#signupform").submit(); in an else block to programmatically submit the form.
$(document).ready(function () {
$("#signupform").submit(function (event) {
event.preventDefault();
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
//Form post data still sent?
} else {
$("#signupform").submit();
}
}
});
}
else alert("Captcha not null");
});
});
You would need have the form event.preventDefault(); before making the ajax request.
$("#signupform").submit(function (event) {
event.preventDefault();
When the ajax request is returned, you can submit the form using:
if (data != 0) {
$("#signupform").submit();
}

Contact form submitting twice

I added a pop up form for email subscription and it is sending twice on submission and the confirmation message is also being displayed twice
Here is the code:
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function(e) {
e.preventDefault();
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(mailvalid == true) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! You have signed up for a trial. A member of our team wil soon be in contact :)</strong></p>");
setTimeout("$.fancybox.close()", 1700);
});
}
}
});
}
});
});
I don't think there's any need to write this line:
$("#contact").submit(function() { return false; }); // Remove this
You can remove this line:
$("#send").on("click", function(){ // Remove this
And write this instead:
$("#contact").submit(function(e) { // Add this
e.preventDefault(); // Add this
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
/* Other code */
});

Email Validation in Javascript Before AJAX

So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

Jquery contact form sends multiple times

I'm trying to create a jquery contact form that sends an ajax request when clicked.
You can view it by visiting: http://childrensplaza.mn, and clicking the "click here to contact us button"
When testing this out though, After I click "send inquiry", it takes a while for the success message to show up, and I'm able to click it multiple times, causing my message to be sent multiple times.
The code for it is below ->
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
// Get the data from the form. Check that everything is completed.
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>
How would I make it so that the success message shows up on the first click, and I am not able to send the same request multiple times?
This is easy enough to handle by adding a class when submitted the first time, and checking if the class is applied to determine whether or not to process the form. If the button already has the class, do not continue to process.
if ( $(this).hasClass("pressed") ) return false;
$(this).addClass("pressed");
Embedded in your code:
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
// Get the data from the form. Check that everything is completed.
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
if ( $(this).hasClass("pressed") ) return false;
$(this).addClass("pressed");
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>
You could take one step further by resetting the class after successful ajax response.
$('#success').fadeIn(500); $("#submit").removeClass("pressed");
you can create a flag and control it with the ajax events beforeSend and complete ...
<script>
$(function(){
$('#trigger').click(function(){
$('#overlay').fadeIn(500);
$('#form').fadeIn(500);
});
$('#overlay').click(function(){
$('#form').fadeOut(500);
$('#overlay').fadeOut(500);
});
});
$('#submit').click(function() {
var email = document.getElementById("email").value;
var inquiry = document.getElementById("inquiry").value;
if( email == "" )
{
alert("Please enter your email.");
return false;
}
if( inquiry == "" )
{
alert("Please enter your inquiry.");
return false;
}
var dataString = 'email=' + email + '&inquiry=' + inquiry ;
$.ajax({
type: "POST",
url: "http://childrensplaza.mn/send.php",
data: dataString,
beforeSend: function(xhr, opts){
if($('#submit').hasClass("posting"))
xhr.abort();
else
$('#submit').addClass("posting");
},
complete: function(){
$('#submit').removeClass("posting");
},
success: function() {
$('#success').fadeIn(500);
}
});
return false;
});
</script>

Categories

Resources