.submit() function not working in jquery - javascript

I am facing on problem my submit function not working I don't know where is the problem. I am using laravel framework 5.2 h
$('#CheckImageCount').on('click', function() {
var arr = [];
$('.table-error').find('tr').each(function() {
if ($(this).find('td:eq(1)').find('select').val() != '') {
if ($(this).find('td:eq(2)').find('select').val() == '') {
arr.push('false');
} else {
arr.push('true');
}
} else {
arr.push('true');
}
});
if ($.inArray('false', arr) > -1) {
swal("Alert!", "Please Select Working Hours in right way!")
return false;
} else {
$.ajax({
type: 'POST',
url: 'CheckImageCount',
success: function(resp) {
if ($.trim(resp) == "empty") {
$('.error-1').fadeIn('fast').delay(1000).fadeOut('fast');
return false;
} else {
$("#registerBusiness").submit(); // here i want to submit the form
}
},
error: function() {}
});
}
});
My form id is registerBusiness it not submit the form even my page not
goto that function here is my form and submit button
<form id="registerBusiness" role="form" method="POST" action="{{ url('/business-for-sale' )}}">{{ csrf_field() }}
And Submit buttton
<button id="CheckImageCount" type="button" class="btn btn-info">Save And Continue </button>

Related

Google captcha v3 button twice click is need to complete action

I just installed recaptcha v3 on a form and I found that the submit button needs to be clicked 2x to make it work.First submit it will get the captcha validation. After the second click it will pass redirect.
Html code
<div class="form_wrpr">
<f:form.hidden id="g-recaptcha-response" property="g-recaptcha-response" />
<button class="g-recaptcha btn btn-blue" id="reg-submit"
data-sitekey="{fields.clientKey}" data-callback='onSubmit' data-action='submit' type= "submit">
{fields.Button}</button>
</div>
Script
$("#reg-submit").on('click', function(){if($('#company').val() == '') {
$('#company_error').text($('#company_error').data("error-mandatory"));
isvalid4 = false;
} if(!isvalid4) {
return false; }
if (grecaptcha.getResponse().length != 0) {
$("#reg-submit").attr("disabled", true);
$.ajax({
type: 'POST',
url: $('#form-ajaxurl').val(),
data: $('#demo_form').serialize(),
success: function(data){
$('#reg-submit').attr("disabled", false);
var output = JSON.parse(data);
if(output.error == 1) {
$('#form-errors').html(output.result);
}
else if(output.error == 2){
$('#form-errors').html(output.result);
} else {
window.location.href = 'test.com'+output.result;
} } }); }else { var elementClicked = 0;
$(".g-recaptcha").on('click', function(){
elementClicked = 1; if( elementClicked == 1)
{ $('#g_captchaerror').text(''); } }); if(elementClicked == 0)
{ isvalid4 = false;
$('#g_captchaerror').text($('#g_captchaerror').data("error-mandatory"));
} } });
The code creates a button that a user must click on in order to complete the CAPTCHA challenge. When the button is clicked, the grecaptcha.execute() function is called, which will trigger the reCAPTCHA v3 verification process.
$(document).ready(function() {
var alreadySubmitted = false;//adding a extra variable to check already submitted.
$("#reg-submit").on('click', function(){
if(!isvalid4) {
return false;
}
grecaptcha.ready(function() {
grecaptcha.execute('clientkey', {
action: 'submit'
}).then(function(token) {
$.ajax({
type: 'POST',
url: $('#form-ajaxurl').val(),
data: $('#demo_form').serialize(),
success: function(data){
// $('#reg-submit').attr("disabled", false);
var output = JSON.parse(data);
if (output.error == 1) {
$('#form-errors').html(output.result);
} else if(output.error == 2) {
$('#form-errors').html(output.result);
} else {
window.location.href = 'test.com'+output.result;
}
}
});
});
});
});

onsubmit return false is not working

The following script shows the error message correctly, but the form always submits whether confirm_shop_code() returns true or false. I tried in many ways to solve the bug but it still persists. I have to stop the form from submitting when it returns false, but allow it to submit when it returns true. Please can any one help me to solve this?
<h2 id="shop_data"></h2>
<!-- form -->
<form action="" class="form-horizontal form-label-left input_mask" method="post" onsubmit="return confirm_shop_code();">
<div class="col-md-4 col-sm-4 col-xs-8 form-group">
<input type="text" class="form-control" id="shop" name="code" value="<?php echo $account->code; ?>" placeholder="Enter Shop Code">
</div>
</form>
<!-- validation script -->
<script>
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
return true;
} else {
return false;
}
}
});
} else {
$( '#shop_data' ).html("");
return false;
}
}
</script>
<!-- php code -->
<?php
include "system_load.php";
$code = $_POST['shop_code'];
global $db;
$query = "SELECT code from accounts WHERE code='".$code."'";
$result = $db->query($query) or die($db->error);
$count = $result->num_rows;
if($count > 0) {
echo "SHOP CODE already Exists";
} else {
echo "OK";
}
exit;
?>
The reason it is submitting is because AJAX calls are asynchronous by default. I wouldn't suggest making it synchronous because this will block the rest of the javascript execution. Also, you are returning false from the success method of $.ajax. This is not in the same scope as the parent function and therefore does not also cause the parent function to return false. So in fact, your confirm_shop_code() function is not returning anything unless code is false and that's why your form is always being submitted, no matter what happens with the AJAX call.
I would recommend using jQuery to bind to the form's submit event and just disable form submitting with preventDefault(). First, just add an id attribute to the form (e.g. "yourform") and do something like:
$("form#yourform").submit(function(e) {
e.preventDefault();
var form = $(this);
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
form.unbind('submit').submit()
}
}
});
} else {
$( '#shop_data' ).html("");
}
});
You need to add async:false to your ajax code
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
var stopSubmit = false;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
async:false,
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
stopSubmit = false;
} else {
stopSubmit = true;
}
}
});
} else {
$( '#shop_data' ).html("");
stopSubmit = true;
}
if(stopSubmit){
return;
}
}
You should call return false; function on the click event of the submit button.
<button type="submit" id="submit" onclick="return false;" class="btn btn-primary col-4">Proceed</button>
or you can use:
document.getElementById("submit").addEventListener("click", function (e) {
//your logic here
//this return false will not work here
return false;
//this will work
e.preventDefault();
});

prompt confirmation box, cancel should stop execution

I have a prompt box, which when i click on delete user, should ask to confirm if he wants to delete the user,
HTML
<form name="myform" id="myform" action="/AWSCustomerJavaWebFinal/DeleteUser" method="POST" onSubmit="myFunction()">
Choose User:
<br>
<select name="selectUser" multiple style="width: 200px !important; min-width: 200px; max-width: 200px;">
<c:forEach var="user" items="${listUsers.rows}">
<option value="${user.id}">
<c:out value="${user.userId}" />
</c:forEach>
</select>
<input type="submit" value="Delete User" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn btn-primary" id=button1>
</form>
javascript
function myFunction() {
var confirm = prompt("Do you want to continue", "yes");
if (confirm == yes) {
var form = $('#myform');
form.submit(function() {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
var result2 = data;
alert("deleted")
}
});
return false;
});
$(document).ready(function() {
$(document).ajaxStart(function() {
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function() {
$("#wait").css("display", "none");
});
});
return false;
} else {
alert("User not deleted")
return false;
}
return false;
}
It asks to confirm, and if I press ok after writing yes in the textbox, it goes to the servlet, and does not give the alert("deleted"), and I have returned false, it still refreshes after pressing submit, also, if i press cancel, it still executes and deletes the user. I tried a lot of different approaches but nothing seems to work here. Thanks in advance.
Try using confirm rather than prompt
var r = confirm("Continue delete?");
if (r == true) {
//your logic to delete
} else {
//alert('user dint delete')
}
A nice one-liner :
if( !confirm("Do you want to continue?") ) return alert("User was not deleted.")
return will stop the execution of the function.
You have a form.submit(function() { $.ajax... that will always trigger your ajax call whenever the form is submitted, regardless of any validation mechanism you set up.
Here is a clean, rewritten version of your code :
in HTML : <form onSubmit="confirmSubmission()"> (a bit more explicit than myFunction() ;)
$(document).ready(function() {
var $wait = $("#wait");
$(document).ajaxStart(function() {
$wait.hide();
}).ajaxComplete(function() {
$wait.show();
});
});
function confirmSubmission() {
if ( !confirm("Do you want to continue")) return alert("Submission has been canceled.")
submit();
}
function submit(){
var $form = $('#myform');
$.ajax({
type : $form.attr('method'),
url : $form.attr('action'),
data : $form.serialize(),
success: function(data) {
var result2 = data;
alert("deleted")
}
});
}

Validating individual form inputs with javascript

I have a registration form that validates a text field, if it's empty when a user clicks/tabs off which shows an error message. My issue with the below code is its a lot to duplicate across several form fields. The below example is for first name but I can't see a way of using what I have to do the same for more than one field.
/* this will call ajax call after entering all the below three fiels */
var $fields = $('#testid');
$fields.live('blur',function(e) {
e.preventDefault();
var $emptyFields = $fields.filter(function() {
return $.trim(this.value) === "";
});
if ($emptyFields.length) {
var frm = $(this).parents('form');
var url=$('#valNameEmail').val();
jQuery.ajax({
url: url,
data: $(this).parents('form').serialize(),
type: 'POST',
dataType: "json",
success: function(response){
if (response.HtmlMessage === 'success'){
$('.reg-alreadyRegistered').html('');
$('.reg-alreadyRegistered').css('display', 'none');
ACC.registration.tickIcon($('#testid'));
var radioExCustValue = $('#registration-form input[name=existingCustomer]:checked').val();
if (userNameAjax === true) {
if (radioExCustValue == 'false'){
$('#regFormSubmit').removeAttr('disabled');
}
else {
if (customerValidation == true){
$('#regFormSubmit').removeAttr('disabled');
}
}
}
emailIDajax = true;
} else {
ACC.registration.errorIcon($('#testid'));
$('.reg-alreadyRegistered').html(response.HtmlMessage);
$('.reg-alreadyRegistered').css('display', 'block');
emailIDajax = false;
$('#regFormSubmit').attr('disabled','disabled');
}
},
error: function(){
//alert(response);
//console.log('ERROR!')
}
});
}
});
You can give the same inputs that require same sort of validation a class (or if you want it for example for all input[type=text] then you can use it for the selector.
So let's say I have a form like this:
<form id="mform">
<input type="text" class="inptxt" name="it1" />
<input type="text" class="inptxt" name="it2" />
<!-- other similar text inputs with the same class -->
<input type="submit" id="sub" value="Submit" />
</form>
I have a function for text inputs which returns false if the field is empty, otherwise true:
$.fn.isValid = function() {
return $.trim($(this).val());
}
And then I get the inputs by class and validate them all at once:
$('#mform').on('submit', function(e) {
e.preventDefault();
var allValid = true;
$('.inptxt').each(function() {
if (!$(this).isValid()) {
$(this).css('background-color', 'red');
allValid = false;
}
else
$(this).css('background-color', 'white');
});
if(allValid) {
//everything's valid ... submit the form
}
});
jsfiddle DEMO
This worked for me:
$('#registration-form input').blur(function(){
if( $(this).val().length === 0 ) {
ACC.registration.errorIcon($(this));
}
else{
ACC.registration.tickIcon($(this));
}
});
thanks for your help

Prevent AJAX form from submitting twice?

I can't figure out why this AJAX form is processing and sending out an email twice. Is there some sort of obvious hickup in the code you can see causing this to occur?
HTML
<form class="submit-form" method="post">
<input type="url" class="content-link" name="content_link" placeholder="Link" />
<input type="email" class="email" name="email" placeholder="Your Email Address" />
<button class="submit-modal-button submit-button"><span>Send<span class="ss-icon">send</span></span></button>
<p class="terms">By clicking Submit you agree to our Terms & Conditions</p>
</form>
JavaScript
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]'),
viewport_size = $(window).width() + "x" + $(window).height(),
user_browser = BrowserDetect.browser,
user_os = BrowserDetect.OS,
current_page = document.location.href;
$('.submit-form input[type="url"],.submit-form input[type="email"]').blur(function () {
if ($.trim($(this).val()) == '') {
$(this).addClass('form-validation-error');
return false;
} else {
$(this).removeClass('form-validation-error');
}
});
form.submit(function () {
if ($.trim(content_link.val()) == '' && $.trim(email.val()) == '') {
content_link.addClass('form-validation-error');
email.addClass('form-validation-error');
return false;
}
else if ($.trim(content_link.val()) == '') {
content_link.addClass('form-validation-error');
return false;
}
else if ($.trim(email.val()) == '') {
email.addClass('form-validation-error');
return false;
} else {
var env = TTB.getEnvironment();
$('.submit-modal-button').attr('disabled','disabled');
$(document).ajaxStart(function () {
$('.submit-modal .screen-1').delay(300).append('<span class="loading2"></span>');
});
$.ajax({
url: env.submit_modal_process,
type: 'POST',
data: {
    content_link: content_link.val(),
    email: email.val(),
viewportsize: viewport_size,
browser: user_browser,
os: user_os,
current_page: current_page
  },
success: function () {
$('.submit-modal .screen-1').delay(1000).fadeOut(300, function () {
$('.submit-modal .screen-1').fadeOut(500, function () {
$('span.loading2').detach();
$('.submit-modal .screen-2').fadeIn(500, function () {
$('.submit-modal .screen-2').append('<img class="carlton" src=' + env.the_environment + TTB.config.image_path() + 'submit-modal-success.gif' + ' />');
});
$('.submit-modal .screen-2').css('display','block').delay(4200).fadeOut(500, function () {
$('.carlton').hide();
$('.submit-modal .screen-1').fadeIn(500);
content_link.val('');
email.val('');
content_link.focus();
email.removeClass('form-validation-error');
$('.submit-modal-button').removeAttr('disabled');
});
});
});
}
});
return false;
}
});
}
EXAMPLE.processSubmitModal();
If to remove all non relevant to the issue code from your snippets we will get the following:
HTML
<form class="submit-form" method="post">
<input type="url" name="content_link" />
<input type="email" name="email" />
<button>Send</button>
</form>
JavaScript
$(function() {
var EXAMPLE = {
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]');
form.submit(function () {
$.ajax({
url: document.location.href,
type: 'POST',
data: {
content_link: content_link.val(),
email: email.val()
},
success: function () { // <-- The function that is executed twice
// Do something
}
});
return false;
});
}
};
EXAMPLE.processSubmitModal();
// And somewhere in the code that was not presented in snippet...
EXAMPLE.processSubmitModal();
});
I played around with your snippet and it always performs only one AJAX call and process email once except the only case - when somewhere in the code you call EXAMPLE.processSubmitModal() once again. Search in your code, I'm almost sure it is the reason. Pay attention that each time you call EXAMPLE.processSubmitModal() you add one another handler to submit event of the form and not override it.
Try like this
form.submit(function (event) {
if(event.handled !== true)
{
//put your ajax code
event.handled = true;
}
return false;
});
Refernce

Categories

Resources