Submit form button stuck after ajax post - javascript

Hi i have a form which uses Ajax to make a post in Rails 4. The javascript runs some validation and should return an alert message once the post is successful. Currently the submit button stays depressed and although the form posts no message gets alerted. I dont know what i'm doing wrong and just want the form to alert a message and then reset itself.
$('#submit1').click(function(e){
e.preventDefault();
var name = $('input#name').val();
if (name == "") {
alert("please enter a name!");
$('input#name').focus();
return false;
}
var email = $('input#email').val();
if (email == ""){
alert("please enter your email");
$('input#email').focus();
return false;
}
var content = $('textarea#text').val();
if (content == ""){
alert("please enter a comment");
$('textarea#text').focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&content=' + content;
$.ajax({
type: "POST",
url: "emailer",
data: dataString,
dataType: 'json',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
success: function(){
alert("mappy jappy");
$('input#name').reset();
$('input#email').reset();
$('textarea#text').reset();
}
});
return false;
});

You are preventing the wrong event. You need the 'onsubmit' event of the form not the 'onclick' event of the submit button.
$('#myform').on('submit', function(event){
event.preventDefault();
/* your code here */
});
For more info please read :
How to prevent form from being submitted?

First of all the reset function is not for the text boxes..it will run for the form. So the corrected code would be...
<script>
$(function(){
$('#submit1').click(function(e){
e.preventDefault();
var name = $('input#name').val();
if (name == "") {
alert("please enter a name!");
$('input#name').focus();
return false;
}
var email = $('input#email').val();
if (email == ""){
alert("please enter your email");
$('input#email').focus();
return false;
}
var content = $('textarea#text').val();
if (content == ""){
alert("please enter a comment");
$('textarea#text').focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&content=' + content;
$.ajax({
type: "POST",
url: "user_availability.php",
data: dataString,
dataType: 'json',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
success: function(){
alert("mappy jappy");
$('#contact-form')[0].reset();
}
});
return false;
});
});
</script>
AND the html part would be like below-
<form id="contact-form" method="post" enctype="multipart/form-data">
<input type="text" id="email" name="email" />
<input type="text" id="name" name="name" />
<textarea name="text" id="text"></textarea>
<input type="submit" value="submit" id="submit1" />
</form>
Please Check and let me know...

Related

validate ajax submit post method before sending data

In this particular case I'm using google tag manager to submit a form within a bootstrap modal.
I don't have access to the backend and this is why I'm using GTM to target a button and use the onClick.
<script>
$(document).on('submit','#MyForm',function(event){
var form = $('#MyForm');
var submit = $('#ssend_btn');
form.on('submit', function(e) {
e.preventDefault();
if($('input', this).val().trim() == '' ){
//handle error message
alert("im empty and email will not send");
}
else if (submit != 'null' ){
event.preventDefault()
var formData = $(this).serialize();
console.log(formData);
$.ajax({
url: "page.php", // some php
data: formData,
datatype: "json",
type: "POST",
success: function(data) {
}
});
}
});
});
</script>
After the email is sent, the modal must not close and this is why I'm using ajax.
If I remove the validation I can send email, but even blank it will submit.
I have other validation with javascript, but is not respecting it.
<script>
function validateForm() {
var x = document.forms["myForm"]["EMAIL"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
error = "testingo";
document.getElementById("errorid").innerHTML = error;
return false;
}
</script>
on console log this is what i get how wever the email is sent
Are you looking for something like this? Looks like you're using a mixture of vanilla JS and jQuery; I'd suggest sticking to one or the other when trying to reference the form and the form inputs, to make it easier.. Also, if you change your input's type to "email" instead of "text", built in browser functionality (for Chrome, etc) will help to ensure a valid email is entered in addition to your validation logic.
function validateForm() {
if ($('#EMAIL').val().trim() === '') {
return false;
}
var x = $('#EMAIL').val();
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
error = "testingo";
document.getElementById("errorid").innerHTML = error;
return false;
}
return true;
}
$(document).ready(function() {
var form = $('#MyForm');
var submit = $('#ssend_btn');
form.on('submit', function(e) {
e.preventDefault();
if (validateForm() === false) {
//handle error message
alert("im empty and email will not send");
} else {
var formData = $(this).serialize();
console.log(formData);
$.ajax({
url: "page.php", // some php
data: formData,
datatype: "json",
type: "POST",
success: function(data) {
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="MyForm" name="MyForm">
<input type="text" name="EMAIL" id="EMAIL" placeholder="EMAIL" />
<div id="errorid"></div>
<input type="submit" id="ssend_btn" value="Submit" />
</form>

Can not get ajax callback to a function

I have a form for user to register new account. I use jquery + ajax to check availability of email address on form submission. In Jquery code I used e.preventDefault(); to prevent form submission if there is any error occurs. I tried the existed email address in the email input and click submit the form. It allows form to submit. It should not do this because ajax reponseText return true means that the email address is already existed in database.
Could anyone please tell me how to fix my code so that if ajax response returns true, it will prevent form submission and shows up errors.
I tried to read and follow this article but fails after so many attempts.
Here is my form:
<form role="form" method="post" id="signupForm" action="index.php?view=signup-gv">
<div class="col-xs-6 border-right">
<div class="form-group">
<label for="exampleInputEmail1">Full Name</label>
<input type="text" class="form-control" id="regname" name="regname" placeholder="Full Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label><span id="emailcheck"></span>
<input type="email" class="form-control" id="regemail" name="regemail" placeholder="Enter email">
</div>
</div>
<div class="form-group col-xs-6">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="regpass" name="regpass" placeholder="Password">
</div>
<button style="position:relative; left: 15px; top: 10px;" class="btn btn-default" name="register" id="register">Register</button>
</form>
Here my jquery code:
$(document).ready(function(){
$('#regname').focus();
$('#signupForm').submit(function(e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
if(regname.val() == ''){
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
e.preventDefault();
}
else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
e.preventDefault();
}
else if(regpass.val() == ''){
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
e.preventDefault();
}
emailCheck().done(function(r){
if(r){
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
e.preventDefault();
}
});
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {regemail:regemail.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'emailcheck.php',
success: function(responseText){
if(responseText == 0){
return false; // good to go
}
else{
emailcheck.html('<span class="errorss"> This email is existed.</span>');
return true; // This email is registered. Please try different one
}
}
});
}
First you are not returning anything from the emailCheck() function, but you are using it as if it is returning a promise object.
So
$(document).ready(function () {
$('#regname').focus();
$('#signupForm').submit(function (e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
//prevent the form submit
e.preventDefault();
if (regname.val() == '') {
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
} else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
} else if (regpass.val() == '') {
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
} else {
emailCheck().done(function (r) {
if (r) {
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
} else {
$('#signupForm')[0].submit();
}
});
}
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {
regemail: regemail.val()
};
var deferred = jQuery.Deferred();
$.ajax({
type: 'POST',
cache: false,
data: UrlToPass,
url: 'emailcheck.php',
success: function (responseText) {
if (responseText == 0) {
deferred.resolve(false);
} else {
emailcheck.html('<span class="errorss"> This email is existed.</span>');
deferred.resolve(true);
}
},
error: function () {
deferred.reject();
}
});
return deferred.promise();
}
You are confusing yourself with sync and async functions. An ajax function makes an Async call and returns output in its callback. You are trying to wrap an Async function inside a normal function and expecting it to behave synchronously.
Your function returns before the Ajax call receives its output. Use
async: false
$.ajax({
type : 'POST',
cache: false,
async: false,
data : UrlToPass,
Refer to following for dettails:
How to make JQuery-AJAX request synchronous

Form submits on keyup after validation, instead of onclick

Here is a JSFiddle which will show the issue that I am having.
Currently, form data gets submitted on keyup as soon as that data is validated, which it should really only submit data when the 'subscribe' button is clicked.
So the form should work like this. If a user clicks the subscribe button, and a particular input fails validation, then that error should be shown. If the user then corrects the error, that specific error should clear on keyup, however, the user should have to click 'subscribe' before the form actually submits any data, or checks for validation again. Currently, the form submits on keyup after passing validation and that should not be the case.
I want to know how I can validate (not submit data) on keyup, as well as validate on click, in addition to submitting data on click.
http://jsfiddle.net/cqf8guys/5/
Code:
$(document).ready(function() {
$('form #response2').hide();
$('.txt1').on('keyup click', function(e) {
e.preventDefault();
var valid = '';
var required = ' is required';
var first = $('form #first').val();
var last = $('form #last').val();
var city = $('form #city').val();
var email = $('form #email').val();
var tempt = $('form #tempt').val();
var tempt2 = $('form #tempt2').val();
if(first=='' || first.length<=1) {
$('form #first').css('border','2px solid #ff0000');
$('form #first').css('background-color','#ffcece');
valid += '<p>Your first name is required</p>';
}
else {
$('form #first').removeAttr('style');
}
if(last=='' || last.length<=1) {
$('form #last').css('border','2px solid #ff0000');
$('form #last').css('background-color','#ffcece');
valid += '<p>Your last name' + required + '</p>';
}
else {
$(this).removeAttr('style');
}
if(city=='' || city.length<=1) {
$('form #city').css('border','2px solid #ff0000');
$('form #city').css('background-color','#ffcece');
valid += '<p>Please include your city</p>';
}
else {
$('form #city').removeAttr('style');
}
if (!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>A valid E-Mail address is required</p>';
}
if (tempt != 'http://') {
valid += '<p>We can\'t allow spam bots.</p>';
}
if (tempt2 != '') {
valid += '<p>A human user' + required + '</p>';
}
if (valid != '') {
$('form #response2').removeClass().addClass('error2')
.html('' +valid).fadeIn('fast');
}
else {
$('form #response2').removeClass().addClass('processing2').html('<p style="top:0px; left:0px; text-align:center; line-height:1.5em;">Please wait while we process your information...</p>').fadeIn('fast');
var formData = $('form').serialize();
submitFormSubscribe(formData);
}
});
});
function submitFormSubscribe(formData) {
$.ajax({
type: 'POST',
url: 'http://3elementsreview.com/blog/wp-content/themes/3elements/php-signup/sign-up-complete.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 4000,
success: function(data) {
$('form #response2').removeClass().addClass((data.error === true) ? 'error2' : 'success2')
.html(data.msg).fadeIn('fast');
if ($('form #response2').hasClass('success2')) {
setTimeout("$('form #response2').fadeOut('fast')", 6000);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('form #response2').removeClass().addClass('error2')
.html('<p>There was an <strong>' + errorThrown +
'</strong> error due to an <strong>' + textStatus +
'</strong> condition.</p>').fadeIn('fast');
},
complete: function(XMLHttpRequest, status) {
$('form')[0].reset();
}
});
};
This is because you have attached your functionality to the wrong event listener type. You don't want $('.txt1').on('keyup click', function(e) {... that's why it is getting mixed up when you deselect something. Instead you want the submit event listener like so....
$('.txt1').on('submit', function(e) {... or $('.txt1').submit(function(e) {...
then if the validation fails you can do an e.preventDefault(); and no form submission will occur.
Here is an example not using your own code...
JAVASCRIPT
var zipSwitch = false;
$(function() {
zipValidate();
validateForm(); //Add Form Submit Validation Event
});
//Constantly Monitor Validation
function zipValidate() {
$("#zip").keyup(function() {
var zipInput = $("#zip").val();
if($.isNumeric(zipInput)) {
$("#msgZone").html("Zip is correct");
$("#msgZone").attr("style", "border-color: rgb(4, 255, 17)");
zipSwitch = true;
} else {
$("#msgZone").html("Zip must be numbers only. Please remove letters.");
$("#msgZone").attr("style", "border-color: rgb(250, 20, 10)");
zipSwitch = false;
}
});
}
//Allow Form To Submit or Not Depending on Validation
function validateForm() {
$("#form1").submit(function(e) {
//If Form Validation Was Correct
if(zipSwitch==true) {
var validCountry = countryValidationFunction();
if(validCountry==true) {
alert("Form Submitted Successfully");
} else if(validCountry==false) {
alert("Please Enter a Valid Country");
e.preventDefault();
}
} else {
e.preventDefault();
}
});
}
HTML
<form name="form1" id="form1" action="#" method="POST" class="span12" style="margin-top: 50px;">
<div id="msgZone" class="well">
Validation Message Zone
</div>
<div class="controls-row">
<span class="help-inline control-list">Zip:</span>
<input id="zip" name="zip" type="text" class="input-medium" required="true" />
</div>
<hr />
<div class="controls-row">
<button type="submit" id="btnSubmit" class="btn btn-success" onSubmit="validateForm()">Submit</button>
<button type="reset" class="btn btn-danger">Reset</button>
</div>
<hr />
</form>

Trigger event on submit

In a newsletter sign-up form, I would like to make the email disappear after the end user hits enter. I have already added JS to hide and unhide the placeholder text.
The code:
<form id="form" action="https://xxxx.com/subscribe/post-json?u=xxx&id=xx&c=?" method="GET">
<input type="hidden" name="u" value="xxx">
<input type="hidden" name="id" value="xxx">
<input id="email" type="EMAIL" autocapitalize="off" autocorrect="off" name="MERGE0" id="MERGE0" size="25" placeholder= "Type your email and press enter">
<p id="response"></p>
</form>
And the JS:
<script >
var text = document.getElementById("email");
text.onfocus = function() {
if ( text.placeholder == "Type your email and press enter") {
text.placeholder = "";
}
};
text.onblur = function() {
if ( text.placeholder == "") {
text.placeholder = "Type your email and press enter";
}
};
</script>
I tried to create a function to trigger the event but it still didn't work:
function checkEnter(event)
{
if (event.keyCode == 13) {text.placeholder = "cool";}
};
Could you all see what's wrong with my code?
Thank you.
You need to add a event listener for the enter key. You could remove your function checkEnter and use this instead:
document.querySelector('#email').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
if (key == 13) {
text.placeholder = "cool";
}
};
I have integrated the code below with the mailchimp form and got the desired results:
var paragraph = document.getElementById('response');
$('#form').submit(function(e) {
var $this = $(this);
$.ajax({
type: "GET", // GET & url for json slightly different
url: "https://xxxxx.com/subscribe/post-json?u=xxxx&id=xxx&c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
paragraph.innerHTML = data.msg;
text.placeholder = "Oopsy daisy! Error :-(";
form.reset();
} else {
paragraph.innerHTML = data.msg;
text.placeholder = "Thanks so much!";
form.reset();
}
}
});
return false;
});

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