Submitting a contact form with sent status on the same page - javascript

I am building a portfolio website and in the contact form, I want a success/fail response after submission. I prefer to stay on the same page whilst this process.
I tried other solutions that were in other pages related to this topic but I could not understand why they did not work for me. Since I am a newbie, I will appreciate a crystal clear explanation. Thanks a lot!
I tried the solution under this topic: Submit contact form with success/fail alert on same page
MY CURRENT HTML CODE IS;
<form id="contact-form" method="post" action="contact.php" role="form" enctype="text/plain">
<div class="messages"></div>
<div class="controls">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="Name *" required="required" data-error="name is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="E-mail *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input id="form_subject" type="text" name="subject" class="form-control" placeholder="Subject">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="send a message."></textarea>
<div class="help-block with-errors"></div>
</div>
<input type="submit" name="submit" class="btn btn-send float-" value="Send message">
<p class="text-muted"><strong>*</strong> These fields are required.</p>
</div>
<div class="clearfix"></div>
</form>
I expect to see confirmation or fail report on the same page after submitting the form. It can be anywhere on the page. I just want the visitor to know that I received their message or could not.

Simple example jQuery version:
$("#contact-form").submit(function() {
var name = $("#form_name").val();
var email = $("#form_email").val();
// ...other fields
// and validation if empty or e-mail is valid etc.
// if validation fails just return false;
if( !name ) {
// here You can send message or activate help-block
return false;
}
// if everything correct use for example ajax from jquery
$.ajax({
url: '/url/to/receiver',
type: 'post',
data: { name: name, .... },
dataType: 'jsonp',
success: function( r ) {
if( r.success ) {
// message and pass form validation
// clear fields, or hide contact form
}
if( r.error ) {
// show error
}
}
});
return false;
});
Remember to return from server JSON like { success: true } or { error: true, msg: "message why fails" }.
But it will be much better, when You will change input type=submit to button, and then make:
$("#contact-form .class-of-input-button").off().on('click', function() { /* rest of the code */ });

Related

How to show the bootstrap 4 validation feedback using jquery?

What I want to achieve is: Getting the form validation information from server using an ajax call and show the errors/invalid feedback inside .invalid-feedback with :invalid css applied to the input fields.
<form id="register-form" novalidate>
<div class="form-group">
<label class="sr-only" for="first_name">first name</label>
<input type="text" id="first_name" name="first_name" value="" class="form-control" >
<div class="invalid-feedback"></div>
</div>
....other inputs
</form>
I was able to set the error messages inside the related invalid-feedback using:
$.ajax({
url: actionUrl,
method: "POST",
dataType: "json",
timeout: 5000,
data: form.serialize(),
success: function (response) {
if(response.errors === ''){
pageRedirect("register/login");
} else {
$.each(response.errors, function(field, error) {
form.find('[name="' + field + '"]').siblings('.invalid-feedback').text(error);
});
//feedback is set now how to show them??
}
},
As documented on Bootstrap's Forms documentation here:
Server side
We recommend using client side validation, but in case you require server side, you can indicate invalid and valid form fields with .is-invalid and .is-valid. Note that .invalid-feedback is also supported with these classes.
In short, you need to add the CSS class is-invalid to form controls that have validation errors. When you do this:
the form control will be surrounded with a red-outline to indicate that it has a validation error
sibling divs with the invalid-feedback CSS class will be rendered as red text
Here's a code snippet illustrating this in action with a "mock" response. Try click the Validate button:
var form = $("form").first();
$("#validate").click(function() {
var mockResponse = {
errors :
{
'first_name': 'First name must not be blank',
'last_name': 'Last name must not be blank'
}
};
$.each(mockResponse.errors, function(fieldName, error) {
let field = form.find('[name="' + fieldName + '"]');
field.addClass("is-invalid");
let immediateSibling = field.next();
if (immediateSibling.hasClass('invalid-feedback')) {
immediateSibling.text(error);
} else {
field.after("<div class='invalid-feedback'>" + error + "</div>")
}
});
return false;
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="bg-light">
<div class="container">
<form id="register-form" novalidate>
<div class="form-group">
<label class="sr-only" for="first_name">First Name</label>
<input type="text" id="first_name" name="first_name" value="" placeholder="First Name" class="form-control" >
</div>
<div class="form-group">
<label class="sr-only" for="last_name">Last Name</label>
<input type="text" id="last_name" name="last_name" value="" placeholder="Last Name" class="form-control" >
</div>
<div class="form-group">
<label class="sr-only" for="email">Email Name</label>
<input type="text" id="email" name="email" value="" placeholder="Email" class="form-control" >
</div>
<button id="validate" class="btn btn-primary btn-lg btn-block" type="submit">Validate</button>
</form>
</div>
https://getbootstrap.com/docs/4.5/components/forms/#custom-styles
As you can see, the script shown there doesn't use AJAX at all. Form validation on the client side is done entirely on the client side.

html form still showing validation errors even after entering right values with javascript

I have a contact form including validations. Everything is working very well but I have only one issue. An old shown error is not going away when submitting the form another time.
Here is the part of the document I have with the javascript:
<form id="contactForm" th:action="#{/contact}" th:method="POST" entype="utf8" >
<label class="form-control-label on-fonts-style display-7" >Name</label>
<input type="text" value="" class="form-control" placeholder="full name" name="fullName" required="required" >
<label class="form-control-label on-fonts-style display-7" >Email</label>
<input type="email" class="form-control" placeholder="Email Address"
name="email" value="" required="required">
<span id="emailError" style="color:#F41F0E"></span>
<label class="form-control-label on-fonts-style display-7" >Phone</label>
<input type="tel" class="form-control" name="phone" placeholder="phone"
value="">
<label class="form-control-label on-fonts-style display-7" >Message</label>
<textarea type="text" class="form-control" name="message" rows="7">
</textarea>
<span id="messageError" style="color:#F41F0E"></span>
<span id="globalError" class="alert alert-danger col-sm-4"
style="display:none" ></span>
<button type="submit" name="submit" class="btn btn-primary btn-form display-
4">SEND FORM</button>
</form>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script th:inline="javascript">
var serverContext = [[#{/}]];
$(document).ready(function () {
$('form').submit(function(event) {
registerContact(event);
});
});
function registerContact(event){
event.preventDefault();
$(".alert").html("").hide();
$(".error-list").html("");
var formData= $('form').serialize();
$.post(serverContext + "contact",formData ,function(data){
if(data.message == "success"){
window.location.href = serverContext + "successContact.html";
}
})
.fail(function(data) {
if(data.responseJSON.error.indexOf("MailError") > -1)
{
window.location.href = serverContext + "emailError.html";
}
else if(data.responseJSON.error.indexOf("InternalError") > -1){
window.location.href = serverContext + "login?message=" + data.responseJSON.message;
}
else{
var errors = $.parseJSON(data.responseJSON.message);
$.each( errors, function( index,item ){
$("#"+item.field+"Error").show().html(item.defaultMessage);
});
errors = $.parseJSON(data.responseJSON.error);
$.each( errors, function( index,item ){
$("#globalError").show().append(item.defaultMessage+"<br/>");
});
}
});
}
</script>
Let me explain: I have two validations (on message and email), so if I typed them wrong the two errors show up. However if I fixed one of them and submit again the old error is still there. Even if I fix them both and submit the form, the form will be submitted but with still showing the errors.
Please anyone have a solution for this problem?
Add a class for all the error spans called error as an example.
when you get to the error checking part you can first hide all errors
$(".error").hide()
and then carry on with the validation as normal :)

Why is my email validation not working in bootstrap and html5?

I have the following form on my page:
<div class="form-group">
<form class="form-horizontal general subscribe" name="commentform" id="subscribe" method="post" action="#">
<div class="col-lg-8 col-md-8 col-xs-8 lower">
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" />
</div>
<div class="col-lg-4 col-md-4 col-xs-4">
<input type="submit" class="btn btn-fill btn-info form_submit" value="Subscribe"/>
</div>
<div id="form_results"></div>
</form>
</div>
and my jquery code for handling the email stuff is as follows:
jQuery(document).ready(function($) {
"use strict";
$('.form_submit').click(function() {
var form = $(this).parents('form');
$.ajax({
url: 'http://mywebservice/mail',
type: "POST",
data: {
email: $('input[name=subscribe_email]').val()
},
dataType:'json',
success: function(response) {
output = '<p>Thanks, we will contact you soon!</p>';
$("#contacts_form .form_item").val('');
form.find('.form_inner').slideUp();
form.find("#form_results").hide().html(output).slideDown();
}
});
return false;
});
});
and now the email is added successfuly to the database each time user presses the Subscribe button, but the problem is that the email is not validated with an official email pattern. I thought that in html5 the only necessary check is this <input type="email" but it does not work properly... How can I prevent users from adding wrong email addresses to the database?
You need to add required attribute for a field to be validated
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" required="required" />
If you submit the form using normal submit button then required fields are validated automatically.
If you are submitting or calling javasript function on submit button then
you can use form.checkValidity() to validate the required controls.
jQuery(document).ready(function($) {
"use strict";
$('.form_submit').click(function(){
var form = $(this).parents('form');
form.checkValidity()
$.ajax({
url: 'http://mywebservice/mail',
type: "POST",
data: {
email: $('input[name=subscribe_email]').val()
},
dataType:'json',
success: function(response)
{
output = '<p>Thanks, we will contact you soon!</p>';
$("#contacts_form .form_item").val('');
form.find('.form_inner').slideUp();
form.find("#form_results").hide().html(output).slideDown();
}
});
return false;
});
});
add required attribute for <input type="email" and sure there is no JavaScript error on the page as well.
You need to add required attribute as per HTML input with type email requires that before it can perform any validation.
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" required />
You can also look into https://jqueryvalidation.org/, I use it and its awesome it allows you show custom message to users

JQuery Form Validation not working properly need fixes?

i'm working with the forms and i want when i hit the submit buttom only that field gets red which are empty . don't knw how to fix it . if anyone can help me i'm new javascript and jquery thanks
My HTML
<form id="form">
<div class="form-group">
<label>Username</label>
<p><span id="usernameError"></span></p>
<input type="text" class="form-control" id="username" placeholder="Username">
</div>
<div class="form-group">
<label>Email</label>
<p><span id="emailError"></span></p>
<input type="email" class="form-control" id="email" placeholder="email">
</div>
<div class="form-group">
<label>Password</label>
<p><span id="passwordError"></span></p>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<p><span id="confPasswordError"></span></p>
<input type="password" class="form-control" id="confPassword" placeholder="Confirm Password">
</div>
<p><span id="warning"></span></p>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
MY JAVASRIPT
now here is the situation . i put all the variables in one if statement and that's why they all are turning into red
$("#form").submit(function(){
if(password.val() != confPassword.val() )
{
alert("password dont match");
}
if($(this).val() == ""){
username.addClass("border");
email.addClass("border");
password.addClass("border");
confPassword.addClass("border");
// warning message
message.text("PLEASE FILL OUT ALL THE FIELDS").addClass("boldred");
// errors rendering
usernameError.text("username must be defined").addClass("red");
emailError.text("email must be valid and defined").addClass("red");
passwordError.text("password must be defined").addClass("red");
confPasswordError.text("confirm password must be matched and defined").addClass("red");
// disabling submit button
submit.attr("disabled" , "disabled");
return false;
}
else{
return true;
}
});
Try JQuery Validation Engine. Its very easy to implement your form.
Validation Engine
Supported for all browsers
First try adding required to all the necessary fields, like:
<input type="text" class="form-control" id="username" placeholder="Username" required>
Then disable (or delete) the if clause.
If that doesn't work, just let me know in the comments and I'll update the answer.
You are approaching the problem in incorrect way.
On Form submit you need to check each field you want separately.
For example:
$("#form").on('submit', function() {
var submit = true;
$(this).find('span').removeClass('red');
$(this).find('input').each(function() {
if ($.trim($(this).val()) === '') {
submit = false;
$(this).parents('.form-group').find('span').addClass('red');
}
});
return submit;
});

The requested was not found on this server - Form validation (Apache/2.4.9 (Win32) PHP/5.5.12 Server at localhost Port 80)

I am trying to create a contact form page using PHP,JQuery, HTML5 and Bootstrap css.
PHP to send mails, JQuery to validate user input and Bootstrap css to highlight the input fields.
In my code i am able to validate the user input but when i click on submit button nothing happens.
In my HTML code when i replace form id from "id=contact-form" to form then i am able to send mails but validation not happen. Please tell me what i am doing wrong.
PHP Code-
<?php
$name= $_POST['name'];
$email= $_POST['email'];
$Message= $_POST['Message'];
$to=" s.nandan#niraame.com , shantanunandan8#gmail.com ";
$from="";
$subject="New query from customer ";
$body = "Customer name : $name\n\n";
$body .= "Customer Message : $Message\n\n";
$body .= "Customer email id : $email\n\n";
ini_set("SMTP","mail.niraame.com");
mail($to,$subject,$from,$body);
?>
HTML Code-
<form method="post" action="contact-form-submission.php" class="form-horizontal" id="contact-form">
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" name="name" id="name" placeholder="Your name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" name="email" id="email" placeholder="Your email address">
</div>
</div>
<div class="control-group">
<label class="control-label" for="subject">Subject</label>
<div class="controls">
<select id="subject" name="subject">
<option value="na" selected="">Choose One:</option>
<option value="service">Feedback</option>
<option value="suggestions">Suggestion</option>
<option value="support">Question</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="message">Message</label>
<div class="controls">
<textarea name="message" id="message" rows="8" class="span5" placeholder="The message you want to send to us."></textarea>
</div>
</div>
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button type="submit" id="submit" class="btn btn-success">Submit Message</button>
<button type="reset" class="btn">Cancel</button>
</div>
</form>
JQuery Code-
$(window).load(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var contact = $("#contact").val();
$.post("contact-form-submission.php", {
name1: name,
email1: email,
mess age1: message,
contact1: contact
}, function(data) {
$("#returnmessage").append(data); // Append returned message to message paragraph.
if (data == "Your Query has been received, We will contact you soon.") {
$("#contact-form")[0].reset(); // To reset form fields on success.
}
});
$(document).ready(function () {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
});
As #jeroen mentioned, currently you are attempting to post the form on page load. Let's try an approach where you submit the form when a user clicks the submit button.
$(document).ready(function () {
// let's attach an event handler to the form's submission
$('#contact-form').submit(function(e) {
e.preventDefault(); // prevent the form from submitting normally, this allows us to interject your client side validation
// perform your validation
// if valid, post
// else show errors, etc
}
});
Also, keep in mind that it's best practice to perform validation both on the server AND the client. At the very least, ALWAYS on the server.

Categories