How to prevent form submit? - javascript

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();
}

Related

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

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 */
});

avoid sending if any field empty Axax

In my form I have various fields including (input and selects) in which I want to check any empty field and prevent ajax call if any of the field is empty and focus on empty fields. so far I am trying this way, It alerts but also makes an ajax call.
$('#submit').click(function() {
$('input').each(function() {
if (!$(this).val()) {
alert('Some fields are empty');
return false;
}
});
event.preventDefault(); // using this page stop being refreshing
$.ajax({
type: 'POST',
url: "<?php echo site_url(''); ?>/shipment/create_shipment",
data: $('form').serialize(),
cache: false,
success: function(data) {
$('#F_id').val('');
$('#v_id').val('');
$('#shp_no').val('');
$('#shipDate').val('');
$('#sup').val('');
$('#sup-quantity').val('');
$('#box').val('');
$('#box-quantity').val('');
$("#sup").prop('disabled', true);
$("#sup-quantity").prop('disabled', true);
$("#box").prop('disabled', true);
$("#box-quantity").prop('disabled', true);
$('.alert-success').fadeOut(200).show();
$('.alert-danger').fadeOut(200).hide();
/// alert('form was submitted');
},
error: function(data) {
$('.alert-success').fadeOut(200).hide();
$('.alert-danger').fadeOut(200).show();
}
});
});
The return false returns from the each function and not the click function.
Try having a bool variable denoting valid, and return false if not.
var valid = true;
e.prevent.preventDefault(); // e being event variable in submit
$('input').each(function() {
if(!$(this).val()){
alert('Some fields are empty');
valid = false;
return false;
}
});
if(!valid) return false;
//.....
Hope this helps.

Message about sent is not working

I have code that checks whether the address is ok and sends it. After sending the information appears that the message was sent.
When I give the wrong email address format - appears the message.
Then when I give the correct address - the message you sent is not working.
What is wrong?
jQuery code:
<script type="text/javascript">
{literal}
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
{/literal}
$(document).ready(function() {
$('#mybtn').click(function() {
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
//e.preventDefault();
}
if (validateEmail(sEmail)) {
$('#contact').submit(function() {
$.ajax({
url : '/contact/process',
data : $('#contact').serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
return false;
});
}
else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
</script>
<script type="text/javascript">
function validateEmail(email) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
}
$(document).ready(function() {
$('#contact').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : '/contact/process',
data : $(this).serialize(),
type: "POST",
success : function(){
$('form').find('#name, #email, #message').val('');
$('#messageAfterSend').addClass('alert alert-success').text("Thank you for send email").slideUp(3200);
}
});
});
$('#mybtn').on('click', function(e) {
e.preventDefault();
var sEmail = $('#email').val();
if ($.trim(sEmail).length == 0) {
alert('Please input your email');
}
if (validateEmail(sEmail)) {
$('#contact').trigger('submit');
} else {
$('#messageAfterSend').addClass('alert alert-success').text("Invalid email.").slideUp(3200);
$('form').find('#email').val('');
}
});
});
Try this way, first set listener on your contact form, second listen for event on "send button"
If it's "simple form" you could just put everything in on('submit') listener
Fiddle

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
});

Categories

Resources