Remove the required attribute after the sucees of form submission - javascript

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.

Related

reCAPTCHA form submitting twice on second submit

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

Mailchimp via jQuery Ajax. Submits correctly but JSON response is returned as a separate page

I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>

Redirection after successful form submit

I have a form which should submit data after pressing the submit button. After tagging a few input fields as required the form always shows me when there is no input in the required field after pressing the submit button - so far, so good.
What I would like to realize is that there is a redirection to another page if the submission was successful. If there are some empty required fields the form should show me, without redirecting me to another page.
By now I have the following code:
Submit button:
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submityes" id="submityes" class="btn btn-danger">Submit</button>
</div>
</div>
Also I have the following js function to submit the form and to redirect me to another page:
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
The problem I have right now is that I will always be redirected to the "submit_resolved.php" page, whether all required fields are complete or not.
How can I solve this problem? I only want to be redirected when all required fields are not empty.
You should bind to the submit event, not click event:
UPDATED TO MATCH THE COMMENTS
$(function () {
var submityesClicked;
//catch the click to buttons
$('#submityes').click(function () {
submityesClicked = true;
});
$('#submitno').click(function () {
submityesClicked = false;
});
$('#webform').submit(function (e) {
e.preventDefault();//prevent the default action
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
window.location.replace(submityesClicked ? "/submit_resolved_yes.php" : "/submit_resolved_no.php");
},
error: function () {
alert("error");
}
});
});
});
The submit event is triggered only if the form is valid.
Note that the submit event is triggered by the form but the click event is triggered by the input element.
Do redirection on complete. Not on success
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
//window.location.replace("/submit_resolved.php");
},
complete: function () {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
I assume you are validating form in process.php so, you have to return error if validation fail from process.php like this.
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
check this link: Return errors from PHP run via. AJAX?
Hope this may be helpful to you.
The simplest thing you can do is to add "required" attribute to you input elements.Example:
<form action="/action_page.php">
Username: <input type="text" name="usrname" required>
<input type="submit">
</form>
It's a HTML5 attribute, so no JavaScript required. And it is supported by all major browsers. Check this link:
http://caniuse.com/#search=required
Anyway, you shouldn't rely just on front-end verification. Check those inputs on back-end, too.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<form action="">
Username: <input type="text" id="usrname" required>
<button type="button" name="submityes"
id="submityes" class="btn btn-danger">Submit</button>
</form>
</div>
function isValid(){
var usrname = $("#usrname").val();
if(usrname == ""){
return false;
}
return true;
}
$(function () {
$('#submityes').submit(function () {
if(isValid() == true){
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
alert("success");
window.location.replace("/submit_resolved.php");
},
});
}else{
alert("error");
}
});
});

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

Run JavaScript if key pressed != ENTER

Im working on a MVC4 site, and I have a webgrid with a search textbox. My Textbox is inside a form, which will be submitted when I press enter. I also have a onkeypress script bound to the textbox, that will, after 3 sek, update my webgrid with what else is entered.
My problem is, that I only want to run the script if not the last key pressed is Enter.
My code looks like this:
#using (Ajax.BeginForm("Filter", new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "projects" }))
{
<div class="paddingTextToleft">
Search:
<input id="searching" name="searchString" type="text" value="" onkeypress="return keypressed()">
<p class="error">#ViewBag.SearchMessage</p>
</div>
<br />
}
And the script:
var timeoutReference;
function keypressed() {
if (window.event.keyCode == 13) {
//Do not run the script!
return true;
}
else {
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function () {
var value = $("#searching").val();
$.ajax({
url: '#Url.Action("Filter", "Project")',
contentType: 'application/html; charset=utf-8',
type: "GET",
dataType: 'html',
data: { searchString: value },
}).success(function (result) {
$('#projects').html(result);
});
}, 3000);
}
};
I want it to stop the script (or not run the rest of it), if the key pressed is enter.
Hope anyone can help me.
Thanks
Firstly you are not sending Event to the function.
Call it with some parameters e.g:
<input id="searching" name="searchString" type="text" value="" onkeypress="keypressed(e)">
Then accept this event in a function:
var timeoutReference;
function keypressed(e) {
if (e.keyCode == 13) {
//Do not run the script!
return;
}
else {
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function () {
var value = $("#searching").val();
$.ajax({
url: '#Url.Action("Filter", "Project")',
contentType: 'application/html; charset=utf-8',
type: "GET",
dataType: 'html',
data: { searchString: value },
}).success(function (result) {
$('#projects').html(result);
});
}, 3000);
}
};

Categories

Resources