reCAPTCHA form submitting twice on second submit - javascript

I am creating a form using reCAPTCHA v2 and want the form to be able to be submitted again without reloading the page. When I submit the form for the first time, it works as expected. However, when I submit the form again without reloading the page, my CaptchaValidate function will be called twice, first returning false, then returning true. Why is this happening? Any help would be brilliant, thanks.
HTML
<form id="form" method="POST">
<label for="name">Name</label>
<input class="form-control" id="name" name="name">
<label for="age">Age</label>
<input class="form-control" id="age" name="age">
<button class="g-recaptcha" data-sitekey="myKey" data-callback="onSubmit" type="submit">Submit</button>
</form>
Javascript
function onSubmit(response) {
$('#form').submit(function (e) {
e.preventDefault();
const formData = $(this).serializeArray();
$.ajax({
url: '/Home/CaptchaValidate',
type: 'POST',
dataType: 'text',
data: { dataToken: response },
success: function (resultData) {
if (resultData == 'true') {
//do something
}
else {
$('.error-message').html('could not submit form');
}
},
error: function (err) {
console.log(err);
}
})
}).submit();
grecaptcha.reset();
}
Controller
[HttpPost]
public async Task<string> GetCaptchaData(string dataToken)
{
HttpClient httpClient = new HttpClient();
string secretKey = "mySecretKey";
var res = httpClient.GetAsync("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + dataToken).Result;
if (res.StatusCode != HttpStatusCode.OK)
return "false";
string JSONres = res.Content.ReadAsStringAsync().Result;
dynamic JSONdata = JObject.Parse(JSONres);
if (JSONdata.success != "true")
return "false";
return "true";
}

try use e.stopImmediatePropagation();
it stops the rest of the event handlers from being executed.
function onSubmit(response) {
$('#form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation(); // new line
const formData = $(this).serializeArray();
$.ajax({
url: '/Home/CaptchaValidate',
type: 'POST',
dataType: 'text',
data: { dataToken: response },
success: function (resultData) {
if (resultData == 'true') {
//do something
}
else {
$('.error-message').html('could not submit form');
}
},
error: function (err) {
console.log(err);
}
})
}).submit();
grecaptcha.reset();
}

Related

jQuery Ajax Email Validator

I have a simple form for a person to fill in their email address. My Ajax script is set to check this address with the database and validate if it exists or not. That step works but I'm stuck on getting the form to submit if the email doesn't exist.
This is my HTML
<form action="user_add.php" method="post" id="addform">
<input
type="text"
class="form-control"
name="email"
id="email"
required
value=""
/>
Check
</form>
This is my JS
function check() {
$.ajax({
url: 'checkusers.php',
data: {
email: $('#email').val()
},
type: 'POST',
dataType: 'json',
success: function (data) {
if (data == true) {
alert('Please note: A user with this email address already exists.')
return false
} else if (data == false) {
//return true; --- this doesn't work
//$('form').submit(); --- this doesn't work
$('form').trigger('submit') // --- this doesn't work
}
},
error: function (data) {
//error
}
})
}
What am I doing wrong here?
Using regular expressions is probably the best way.
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function check(){
var email = $('#email').val();
if (validateEmail(email)) {
$.ajax({
url: "checkusers.php",
data: {
'email' : email
},
type: "POST",
dataType: 'json',
success: function(data) {
if(data == true) {
alert('Please note: A user with this email address already exists.');
return false;
}
else if(data == false) {
//return true; --- this doesn't work
//$('form').submit(); --- this doesn't work
$('form').trigger('submit'); // --- this doesn't work
}
},
error: function(data){
//error
}
});
} else {
// error email not valid
}
}
Thank you to everyone for your input. I had a stray submit button higher up on the page I was working on
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-primary">
When I took this out, the following bit worked:
$('form').trigger('submit');

Different Form Submit Actions for Different Forms

Super basic javascript question incoming...
I have two forms, one for uploading a file and one for providing text. I want to have a unique submit action for each of these forms. For the former, to upload the file, and for the latter, to serialize the form into JSON and POST it.
To attempt to accomplish this, I have one function called submit and another called submit2. The file upload form, which invokes submit works just fine.
The problem is with the second form, which invokes submit2. In particular, when I load the page, I get the following errors:
Query.Deferred exception: undefined is not a function (near '...$('form').submit2...').
TypeError: undefined is not a function (near '...$('form').submit2...')
Here's my HTML.
Upload an image
<form method="POST" enctype="multipart/form-data" action="upload">
<input id="img" name="file" type="file" accept=".jpeg,.jpg,.png">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
Paste a URL
<form method="POST" name="urlForm" onclick="submit2()">
<input id="imgurl" name="url" type="text">
<input class="btn btn-primary" value="Submit">
</form>
And here's my javascript.
function ConvertFormToJSON(form){
var array = jQuery(form).serializeArray();
var json = {};
console.log(array)
jQuery.each(array, function() {
json[this.name] = this.value || '';
});
return json;
}
$(document).ready(function () {
var $status = $('.status');
$('#img').change(function (event) {
var obj = $(this)[0];
console.log(obj)
$status.html('');
if (obj.files && obj.files[0]) {
console.log(obj.files)
var fileReader = new FileReader();
fileReader.onload = function (event) {
$('.img-area').html(
`<img class='loaded-img' src='${event.target.result}' style="width:500px;height:500px;"/>`
);
}
fileReader.readAsDataURL(obj.files[0]);
}
});
$('#imgurl').change(function (event) {
var obj = $('#imgurl').val()
console.log(obj)
$('.img-area').html(
`<img class='loaded-img' src='${obj}' style="width:500px;height:500px;"/>`
);
});
$('form').submit(function (event) {
event.preventDefault();
var imageData = new FormData($(this)[0]);
console.log(imageData)
$status.html(
`<span class='eval'>Evaluating...</span>`
);
$.ajax({
url: 'some_api_endpoint',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
data: imageData,
success: function (responseData) {
console.log(responseData)
if (responseData.error != null) {
$status.html(
`<span class='result failure'>Failed</span>`
);
} else {
$status.html(
`<span class='result success'>${responseData.message}</span>`
);
}
},
error: function () {
$status.html(
`<span class='eval'>Something went wrong, try again later.</span>`
);
}
});
});
$('form').submit2(function (event) {
event.preventDefault();
var json = ConvertFormToJSON($('form'))
console.log(json)
$status.html(
`<span class='eval'>Evaluating...</span>`
);
$.ajax({
url: 'some_api_endpoint',
type: 'POST',
processData: false,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json),
success: function (responseData) {
console.log(responseData)
if (responseData.error != null) {
$status.html(
`<span class='result failure'>Failed</span>`
);
} else {
$status.html(
`<span class='result success'>${responseData.message}</span>`
);
}
},
error: function () {
$status.html(
`<span class='eval'>Something went wrong, try again later.</span>`
);
}
});
});
});
Edit: Added the ConvertFormToJSON function for completeness, although I think that's orthogonal to the issue I'm facing.
Problem in there Jquery Object dont have submit2 method and when you want to access submit2 method this is return undefined and when call this is return undefined is not function.

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

Show Json Data after pushing Enter instead of Click ob submit

I have a MVC view that by clicking on submit button it post Data using Ajax to the Controller. The controller return json result that is messages and I show them on the View. The problem is when I click on Submit button it working fine but when I push Enter after show the Thank you page again it post to the controller method and show a page with json Data as bellow: (I need to make the Enter work as pushing Submit as well)
{"status":"success","message":""}
This is my View:
#using (Html.BeginForm("forgotPassword", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div>
<div>Email Address</div>
<div><input type="email" name="email" placeholder="example#email.com" id="email" class="forgot-password-textbox"></div>
<div><label id="Message" class="forgot-password-error-message"></label></div>
<div><input type="button" value="Submit" id="btn-reset-password" onclick="resetPasswordHandler()" class="orange-button forgot-password-button"></div>
</div>
}
This is my Controller Method:
[HttpPost]
[Route("forgotPassword")]
public async Task<JsonResult> ForgotPassword(ForgotPasswordRequest forgotPasswordRequest)
{
...
try
{
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(forgotPasswordRequest.Email))
{
users = await authenticationService.GetUserByEmailAsync(forgotPasswordRequest.Email);
if (users.Any())
{
if(users.FirstOrDefault().StatusId == 2)
{
return Json(new { status = "error", message = Constants.MessageStrings.ForgotPasswordDisabledUser });
}
//New User without creating password
if (string.IsNullOrEmpty(users.FirstOrDefault().PasswordHash))
{
return Json(new { status = "error", message = Constants.MessageStrings.ForgotPasswordDisabledUser });
}
....
}
}
else
{
ModelState.AddModelError("", Constants.MessageStrings.NoUser);
return Json(new { status = "error", message = Constants.MessageStrings.NoUser });
}
}
}
else
{
.......
return Json(new { status = "error", message = Constants.MessageStrings.RequiredFields });
}
and this is my Ajax to call controller:
function resetPasswordHandler() {
var postResult = null;
var data = {
Email: document.getElementById('email').value
};
var path = "/forgotPassword";
var errorMessage = document.getElementById('Message');
$.ajax({
dataType: "text",
url: path,
data: data,
type: "POST",
cache: false,
success: function (result) {
postResult = $.parseJSON(result);
if (postResult.status == "success") {
$('#forgot').hide();
$('#forgot-thank-you').show();
return false;
}
else {
errorMessage.innerHTML = postResult.message;
}
},
error: function () {
errorMessage.innerHTML = "An error occured";
}
});
return false;
};
window.onkeydown = function () {
if (window.event.keyCode == '13') {
resetPasswordHandler();
}
}
return Json(new { status="success",message="what ever your msg"}, JsonRequestBehavior.AllowGet);
I would remove the click handler from the button, and handle the submit event of the relevant form.
You should give an id for easier targeting
#using (Html.BeginForm("forgotPassword", "Home", FormMethod.Post, new { id = "reset-form" }))
And simplify your script (since you are using jQuery) to
function resetPasswordHandler(event) {
var postResult = null,
data = {
Email: $('#email').val()
},
path = "/forgotPassword",
errorMessage = $('#Message');
event.preventDefault();
$.ajax({
dataType: "text",
url: path,
data: data,
type: "POST",
cache: false,
success: function(result) {
postResult = $.parseJSON(result);
if (postResult.status == "success") {
$('#forgot').hide();
$('#forgot-thank-you').show();
return;
} else {
errorMessage.html(postResult.message);
}
},
error: function() {
errorMessage.html("An error occured");
}
});
return false;
};
$('#reset-form').on('submit', resetPasswordHandler);

Magento newsletter ajax request returns null

I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});

Categories

Resources