<form id='formregister' autocomplete='off'>
<input type='text' name='user' maxlength='50' placeholder='* Username'>
<input type='text' name='pass' maxlength='50' placeholder='* Password'>
<input type='text' name='name' maxlength='50' placeholder='Ime'>
<button id='btnregister'>Register</button>
</form>
javascript
$('#btnregister').click(function(){
$.ajax({
url: 'regpro.php',
type: 'post',
data: $('#formregister').serialize(),
success: function(data) {
if (data == 'exists') {
alert ('user already exists'); // after closing form is empty!
}
else if (data =='empty'){
alert ('something is missing'); // after closing form is empty!
}
else{
if (window.confirm('Registration is successfull. Do you wont to login?')){
window.location.href = 'login.php'; // doesn't work
}
else {
window.location.href = 'index.php'; // doesn't work
}
}
}
});
});
So why form inputs become empty after closing alert, and why redirections don't work after confirm dialog is closed ?
You should add event.preventDefault(); to your code:
$('#btnregister').click(function(event){
event.preventDefault();
...
});
This method will disable the default submit action of the form when you click on the button.
I am trying to do some basic validation for a simple newsletter form I have that only requires an email. The way I have this form/input within the page, there really isn't room to add any jQuery validate error messages, so I was trying to add a simple HTML 5 required attribute, but the form submits regardless if blank.
What would be the best way to add some simple validation to this so the form checks for an email address, it is filled in, and min length of 4 characters?
<form action="" method="POST" id="newsletter-form">
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" required>
<input type="submit" id="footer-grid1-newsletter-submit" name="submit" value=' '>
</form>
$("#footer-grid1-newsletter-submit").on("click", function (event) {
event.preventDefault();
var newsletter_email = $("#footer-grid1-newsletter-input").val();
var targeted_popup_class = jQuery(this).attr('data-popup-open');
$.ajax({
url: "newsletterSend.php",
type: "POST",
data: {
"newsletter_email": newsletter_email
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert email!");
alert(data);
} else {
$("#newsletter-form")[0].reset();
$('.newsletter-popup').fadeIn(350).delay(2000).fadeOut();
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
The reason is because the validation is done on the submit event of the form, yet you have hooked your event to the click of the submit button. Try this:
$("#newsletter-form").on("submit", function (event) {
event.preventDefault();
// your code...
});
Working example
With regard to validating a minimum input length, you can use the pattern attribute:
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" pattern=".{3,}" required>
I have created a submission form using Expression engine's plugin freeform, everything is working in terms of submission, the only issue i am having is the valuation side of things.
Is there a way to validate my script before submission, i.e pick up things as unfilled fields, incorrect emails etc..
below is a snippet of my code.
JQUERY
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
if (response.success) {
formMessages.removeClass('error').addClass('success').text("Thank you for submitting your details");
$('.valFields').val("");
} else {
formMessages.removeClass("success").addClass("error").text("Oops, Please check your details");
}
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
})
});
HTML
<div id="form-messages">
{exp:freeform:form
form_id="1"
admin_notify="myemail#.me.com"
form:class="main-contact submit-fade ajax-form"
form:id="ajax-contact"
}
<ul class="small-block-grid-2 medium-block-grid-2 hide-form">
<li>
<label for="name">Name</label>
{freeform:field:first_name
attr:class="form-control valFields"
attr:placeholder="First Name"
attr:class="required"
}
</li>
<li>
<label for="email">Email</label>
{freeform:field:email
attr:class="form-control valFields"
attr:placeholder="Email"
attr:class="required"
}
</li>
</ul>
<input type="submit" class="btn btn-success">
{/exp:freeform:form}
</div>
</div>
</div>
Validation of fields can done calling a function
Call Validate function onSubmit action and if successful perform the submission of form using AJAX.
Example:
<script>
$(form).submit(function(e) {
e.preventDefault();
var check = validate();
if(check){
var formData = $(form).serialize();
..
//form sumit using AJAX
..
}
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
return true;
}
</script>
The better way of doing this is putting types in inputs
<ul class="small-block-grid-2 medium-block-grid-2 hide-form">
<li>
<label for="name">Name</label>
{freeform:field:first_name
attr:class="form-control valFields"
attr:placeholder="First Name"
attr:required="required"
}
</li>
<li>
<label for="email">Email</label>
{freeform:field:email
attr:class="form-control valFields"
attr:placeholder="Email"
attr:required="required",
attr:type="email"
}
</li>
</ul>
It will not only make sure that the fields are not left empty but also will check the valid email type.
I have a comment form which insert data to a database upon submitting. Following is the code;
function reloadRecaptcha() {
var publicKey = "*************************************";
var div = "recap";
Recaptcha.create(publicKey,div,{theme: "white"});
return false;
}
function validateForm() {
var x=document.forms["cmnts"]["name"].value;
if (x==null || x=="") {
jAlert('Please enter your name', 'Error');
return false;
}
var x=document.forms["cmnts"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
jAlert('Please enter a valid email address', 'Error');
return false;
}
var x=document.forms["cmnts"]["comment"].value;
if (x==null || x=="") {
jAlert('Please enter a comment', 'Error');
return false;
}
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
$.ajax({
type: "POST",
url: "includes/valrecaptcha.php",
async: false,
data: {
challenge: challenge,
response: response
},
success: function(resp) {
if(resp == "false") {
jAlert('Please enter captcha words correctly', 'Error');
reloadRecaptcha();
}
}
});
}
Everything (such as form validating works fine except when I hit the submit button, the comment is posted no matter the reCAPTCHA is correct or not. Right before the page starts navigating, I see the alert message. I'm using jAlert to display alert messages. Following is the form;
<h4>Leave your comment</h4>
<form action="blog?post=".$_GET["post"]."#comments" onsubmit="return validateForm();" name="cmnts" method="post">
<div class="form_row">
<label>Name</label><br />
<input type="text" class="tbox" name="name" title="Type your name"/>
</div>
<div class="form_row">
<label>Email (not visible to others)</label><br />
<input type="text" class="tbox" name="email" title="Type your email" />
</div>
<div class="form_row">
<label>Comment</label><br />
<textarea name="comment" class="tbox" rows="6" title="Type your comment" ></textarea>
<p>You may use following HTML tags and attributes: <b> <cite> <del> <i> <u></p>
</div>
<div class="form_row" style="height:80px;">
<label>Captcha</label><br />
<div id="recap"></div>
<p>I must make sure that you're <i>not</i> a spammer or a bot</p>
<div style="clear:both;">
</div>
<input value="Comment" id="submit" name="submit" class="submit_btn float_l" type="submit">
</form>
The <body> tag has an onload event return reloadRecaptcha();
So why doesn't the form get submitted before validating the reCAPTCHA?
This happens because validateForm() does not return anything from the ajax call. You should have a variable like isCaptchaValidated, and set that inside the success() of ajax, and then return that variable after the ajax like below:
var isCaptchaValidated = false;
$.ajax({
type: "POST",
url: "includes/valrecaptcha.php",
async: false,
data: {
challenge: challenge,
response: response
},
success: function(resp) {
if(resp == "false") {
jAlert('Please enter captcha words correctly', 'Error');
reloadRecaptcha();
} else {
isCaptchaValidated = true;
}
}
});
return isCaptchaValidated;
By the way, ajax means Asynchronous JavaScript and XML, so I would go against setting async: false.
I am using the following script for validate my contact form.
//submission scripts
$('.contactForm').submit( function(){
//statements to validate the form
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById('e-mail');
if (!filter.test(email.value)) {
$('.email-missing').show();
} else {$('.email-missing').hide();}
if (document.cform.name.value == "") {
$('.name-missing').show();
} else {$('.name-missing').hide();}
if (document.cform.phone.value == "") {
$('.phone-missing').show();
}
else if(isNaN(document.cform.phone.value)){
$('.phone-missing').show();
}
else {$('.phone-missing').hide();}
if (document.cform.message.value == "") {
$('.message-missing').show();
} else {$('.message-missing').hide();}
if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "") || isNaN(document.cform.phone.value)){
return false;
}
if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
//hide the form
//$('.contactForm').hide();
//show the loading bar
$('.loader').append($('.bar'));
$('.bar').css({display:'block'});
/*document.cform.name.value = '';
document.cform.e-mail.value = '';
document.cform.phone.value = '';
document.cform.message.value = '';*/
//send the ajax request
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
});
//waits 2000, then closes the form and fades out
//setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);
//stay on the page
return false;
}
});
This is my form
<form action="mail.php" class="contactForm" id="cform" name="cform" method="post">
<input id="name" type="text" value="" name="name" />
<br />
<span class="name-missing">Please enter your name</span>
<input id="e-mail" type="text" value="" name="email" />
<br />
<span class="email-missing">Please enter a valid e-mail</span>
<input id="phone" type="text" value="" name="phone" />
<br />
<span class="phone-missing">Please enter a valid phone number</span>
<textarea id="message" rows="" cols="" name="message"></textarea>
<br />
<span class="message-missing">Please enter message</span>
<input class="submit" type="submit" name="submit" value="Submit Form" />
</form>
I need to clear the form field values after submitting successfully. How can i do this?
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
You can do this inside your $.post calls success callback like this
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
//clear fields
$('input[type="text"],textarea').val('');
});
use this:
$('form.contactForm input[type="text"],texatrea, select').val('');
or if you have a reference to the form with this:
$('input[type="text"],texatrea, select', this).val('');
:input === <input> + <select>s + <textarea>s
$('.contactForm').submit(function(){
var that = this;
//...more form stuff...
$.post('mail.php',{...params...},function(data){
//...more success stuff...
that.reset();
});
});
Simply
$('#cform')[0].reset();
it works: call this function after ajax success and send your form id as it's paramete. something like this:
This function clear all input fields value including button, submit, reset, hidden fields
function resetForm(formid) {
$('#' + formid + ' :input').each(function(){
$(this).val('').attr('checked',false).attr('selected',false);
});
}
* This function clears all input fields value except button, submit, reset, hidden fields
* */
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
example:
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#alertt').fadeIn(2000);
$('#alertt').html( data );
$('#alertt').fadeOut(3000);
resetForm('userInf');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#userInf').submit( processForm );
})(jQuery);
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
</script>
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
http://www.electrictoolbox.com/jquery-clear-form/
Set id in form when you submitting form
<form action="" id="cform">
<input type="submit" name="">
</form>
set in jquery
document.getElementById("cform").reset();
$('#formid).reset();
or
document.getElementById('formid').reset();
Vanilla!
I know this post is quite old.
Since OP is using jquery ajax this code will be needed.
But for the ones looking for vanilla.
...
// Send the value
xhttp.send(params);
// Clear the input after submission
document.getElementById('cform').reset();
}
just use form tag alone, like this :
$.ajax({
type: "POST",
url: "/demo",
data: dataString,
success: function () {
$("form")[0].reset();
$("#test").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$("#message").append(
"<img id='checkmark' src='images/check.png' />"
);
});
}
});
e.preventDefault();
});
Using ajax reset() method you can clear the form after submit
example from your script above:
const form = document.getElementById(cform).reset();
If you are using a form tag in your form. Then
$("#cform")[0].reset();
This code will work perfectly but in case you are not using any form tag then you can try to set an empty value to each input field Like this.
$('input[type="text"],textarea').val('');