Validating forms Ajax PHP - php

The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.
contact form index.html
<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<div id="errormessage"></div>
<form action="contactform/contactform.php" method="POST" role="form" class="contactForm">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
contactform.js
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function() {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var action = $(this).attr('action');
if( ! action ) {
action = 'contactform/contactform.php';
}
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
//alert(msg);
if (msg == 'OK') {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
} else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
contactform.php
<?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');
//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;
//Add new message
if (isset($_POST['name'])){
//Get values
$contactFormName = $_POST['name'];
$contactFormEmail = $_POST['email'];
$contactFormSubject = $_POST['subject'];
$contactFormMessage = $_POST['message'];
// 1. check name form field
if($checkStep == 1){
if($contactFormName === $_POST['name']){
$contactFormName = filterName($contactFormName);
$checkStep++;
}else{
echo "No its not working";
}
}
// 2. check email field
if($checkStep == 2){
if($contactFormEmail === $_POST['email']){
$contactFormEmail = filterEmail($contactFormEmail);
$checkStep++;
}else{
echo "Uh Oh! Something went wrong with your email please try again!";
}
}
// 3. check subject
if($checkStep == 3){
if($contactFormSubject === $_POST['subject']){
$contactFormSubject = filterSubject($contactFormSubject);
$checkStep++;
}else{
echo "Uh Oh! Whats up with your subject";
}
}
// 4. check message
if($checkStep == 4){
if($contactFormMessage === $_POST['message']){
$contactFormMessage = filterMessage($contactFormMessage);
$checkStep++;
}else{
echo "Uh ho! Please write us a message";
}
}
// 5. insert message
if($checkStep == 5){
$sqlAddMessage = "
INSERT INTO contact_form(
name,
email,
subject,
message
) VALUES(
'$contactFormName',
'$contactFormEmail',
'$contactFormSubject',
'$contactFormMessage'
)
";
$queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);
if($queryAddMessage){
//code goes here
}
}else{
echo "Uh Oh! NO No No. Check step 5";
}
}
?>

The issue is that you're not setting $msg = "OK" anywhere in your function so the AJAX response is always going to the else statement.
contactform.php (in // 5. section)
if($queryAddMessage){
echo "OK";
}

You should echo msg checked by js in php as OK
if($queryAddMessage){
//code goes here
echo 'OK';
}

Just use a jQuery form validation plugin to validate form and its easier than using AJAX for the same.

Related

Redirect page after echo [duplicate]

This question already has answers here:
How do I redirect to another webpage?
(58 answers)
How do I make a redirect in PHP?
(34 answers)
Reference - What does this error mean in PHP?
(38 answers)
Page redirect after certain time PHP
(9 answers)
Closed 2 years ago.
I have checked How do I redirect to another webpage? and though they do successfully redirect, they remove the echo 'OK' function I have implemented.
I have a form and would like to redirect back to the home page 5 seconds after the form has been submitted.
However, there needs to be an echo first that says "OK" which links to a jQuery script and shows a green box that says "Your message has been sent (<div class="sent-message">). Thank you!". I would like to display that for 5 seconds, before redirecting back to the home page.
I know you cannot use header("Location: http://www.yourwebsite.com/index.html"); after echo but is there another way to do this?
This is what the form looks like when it is successfully submitted. The green box is what echo 'OK'; does. https://ibb.co/BjZ9v47
contact.php
<?php
// script to send myself an email with the data entered into the form by a user
if($mail->Send()) {
echo 'OK';
// redirect to index.html after 5 seconds
}
?>
form.html
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="captcha">
<div class="g-recaptcha" data-sitekey="my_site_key" data-callback="removeFakeCaptcha"></div>
<input type="checkbox" class="captcha-fake-field" tabindex="-1" required>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" title="Send Message">Send Message</button></div>
</form>
jQuery script:
!(function($) {
"use strict";
$('form.php-email-form').submit(function(e) {
e.preventDefault();
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
if ( $(this).data('recaptcha-site-key') ) {
var recaptcha_site_key = $(this).data('recaptcha-site-key');
grecaptcha.ready(function() {
grecaptcha.execute(recaptcha_site_key, {action: 'php_email_form_submit'}).then(function(token) {
php_email_form_submit(this_form,action,this_form.serialize() + '&recaptcha-response=' + token);
});
});
} else {
php_email_form_submit(this_form,action,this_form.serialize());
}
return true;
});
function php_email_form_submit(this_form, action, data) {
$.ajax({
type: "POST",
url: action,
data: data,
timeout: 40000
}).done( function(msg){
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
if(!msg) {
msg = 'Form submission failed and no error message returned from: ' + action + '<br>';
}
this_form.find('.error-message').slideDown().html(msg);
}
}).fail( function(data){
console.log(data);
var error_msg = "Form submission failed!<br>";
if(data.statusText || data.status) {
error_msg += 'Status:';
if(data.statusText) {
error_msg += ' ' + data.statusText;
}
if(data.status) {
error_msg += ' ' + data.status;
}
error_msg += '<br>';
}
if(data.responseText) {
error_msg += data.responseText;
}
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(error_msg);
});
}
})(jQuery);
You can echo a <meta> refresh with a set URL, although this isn't the best approach.
if (!$mail->Send()) {
echo "Mail sending failed";
}
else {
echo "Mail sent!";
echo "<meta http-equiv='refresh' content='5;URL=/index.html'>";
}
More information about the meta tag here.
In your $.ajax done callback, inside if you can use setTimeout:
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
//redirect to specific url after 5secs
window.setTimeout(function () {
window.location.href = 'https://www.example.com'; //your home url here
}, 5000);
}

Echo div class after form is submitted

I have a contact form on my website. When a user presses submit with their details filled it, it sends me an email. However, when they click submit, a green box should appear below <div class="sent-message"> yet, when I click submit, it shows a red box and says, "mail sent". Here are the PHP lines in contact.php that are causing this...
Simply, the box should be changed to green and have the text from sent-message instead of this.
if($mail->Send()) {
echo "mail sent";
}
else {
echo "mail sent failed";
}
<div class="form">
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" title="Send Message">Send Message</button></div>
</form>
</div>
Here is the jQuery:
!(function($) {
"use strict";
$('form.php-email-form').submit(function(e) {
e.preventDefault();
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
if ( $(this).data('recaptcha-site-key') ) {
var recaptcha_site_key = $(this).data('recaptcha-site-key');
grecaptcha.ready(function() {
grecaptcha.execute(recaptcha_site_key, {action: 'php_email_form_submit'}).then(function(token) {
php_email_form_submit(this_form,action,this_form.serialize() + '&recaptcha-response=' + token);
});
});
} else {
php_email_form_submit(this_form,action,this_form.serialize());
}
return true;
});
function php_email_form_submit(this_form, action, data) {
$.ajax({
type: "POST",
url: action,
data: data,
timeout: 40000
}).done( function(msg){
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
if(!msg) {
msg = 'Form submission failed and no error message returned from: ' + action + '<br>';
}
this_form.find('.error-message').slideDown().html(msg);
}
}).fail( function(data){
console.log(data);
var error_msg = "Form submission failed!<br>";
if(data.statusText || data.status) {
error_msg += 'Status:';
if(data.statusText) {
error_msg += ' ' + data.statusText;
}
if(data.status) {
error_msg += ' ' + data.status;
}
error_msg += '<br>';
}
if(data.responseText) {
error_msg += data.responseText;
}
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(error_msg);
});
}
})(jQuery);
You could do something like this, in contact.php:
$sent = false;
if($mail->Send()) { $sent = true; }
Then in your html you show message:
<?php
if($sent) { ?>
<div class="sent-message">Your message has been sent. Thank you!</div>
<?php } ?>
UPDATE
So your form submission is controlled by jQuery. You can show message by just echo 'OK' instead of "mail sent" in your php script
if($mail->Send()) {
echo "mail sent";
$color = 'green';
}
else {
echo "mail sent failed";
$color = 'red';
}
?>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message" style='background-color:"<?php echo $color;' ?>">Your message has been sent. Thank you!</div>
</div>
Your code must return
if($mail->Send()) {
echo "OK";
}
and if you want differen message, you can change it here:
<div class="sent-message">My new message</div>

Php Ajax and html5 form integration of contact form

I am having experience in PHP and HTML but not much familiar with Ajax. Can anyone help me out here to integrate my contact form, please check my code below what modification can be required in PHP and ajax code. If I remove ajax its working fine after including ajax form is not getting posted
HTML Code
<div class="col-lg-6">
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
Php code
<?php
require_once 'include/DB_Functions.php';
require 'send-grid/vendor/autoload.php';
$db = new DB_Functions();
if (isset($_POST['contact'])){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($db->storeform($name,$email,$phone,$subject,$message)) {
$memail = new \SendGrid\Mail\Mail();
$memail->setFrom("info#probig.in", "Probig Consulting");
$memail->setSubject("We have received your message");
$memail->addTo($email);
$raw_html = file_get_contents('email.html');
$getvar= array('%name%');
$repvar= array($name);
$femail=str_replace($getvar, $repvar, $raw_html);
$memail->addContent( "text/html", $femail);
$sendgrid = new \SendGrid('key');
try {
$response = $sendgrid->send($memail);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
$email2 = new \SendGrid\Mail\Mail();
$email2->setFrom("noreply#probig.in", "Probig Consulting");
$email2->setSubject($subject);
$email2->addTo("info#probig.in");
$email2->addContent("text/plain", "Name:".$name."<br><br>Mobile:".$phone."<br><br>Message:".$message);
$sendgrid = new \SendGrid('Key');
try {
$response = $sendgrid->send($email2);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
header("Location:msgsent.html");
}else{
echo "cant send message";
}
}
?>
AJax code:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.php-email-form').submit(function() {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg) {
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(msg);
}
}
});
return false;
});
});

php form action and jquery validation executing at once

My jquery validation and php form are both executing at once, means the validations errors are showing and also the php action is executed. here is the complete code. The jquery form submit function is returning false if the there are errors in form but even thought the form getting executed..
<form class="form-3 form-horizontal ajxfrm " id="step-three" enctype="multipart/form-data" action="<?php echo $html->addLink(array('controller'=>'homes','action'=>'step_three')); ?>" method="post" target="_parent">
<div id="calendar">
<div class="clear"></div>
<div class="control-group">
<div class="control-label">Name<span>*</span></div>
<div class="controls"><input type="text" name="name" id="name" />
<span id="nameInfo"></span></div>
</div>
<div class="control-group">
<div class="control-label">Email<span>*</span></div>
<div class="controls"><input type="text" name="email" id="email" />
<span id="emailInfo"></span></div>
</div>
<div class="control-group">
<div class="control-label">Contact<span>*</span></div>
<div class="controls"><input type="text" name="contact" id="contact" />
<span id="contactInfo"></span></div>
</div>
<div class="control-group">
<div class="control-label">Skype Id<span>*</span></div>
<div class="controls"><input type="text" name="skypeid" id="skype" />
<span id="skypeInfo"></span></div>
</div>
<div style="position:relative">
<div class="control-group">
<div class="control-label">Files<br/><span style="font-size:10px; font-style:italic">(Optional)</span></div>
<div class="controls">
<input id="fileupload" type="file" name="fileupload[]" multiple/>
<span id="fileInfo"></span><br/>
</div>
</div>
</div>
<div class="control-group">
<div class="control-label">Your Message<span>*</span></div>
<div class="controls"><textarea rows="3" name="message" id="message"></textarea>
<span id="messageInfo"></span></div>
</div>
<div class="clear"></div>
</div>
<div id="submit" style=" text-align:right;">
<input type="hidden" name="post" value="1"/>
<input type="submit" class="btn green" value="Next" id="step3submit" style="margin-right:-20%; margin-top:5%"/>
</div>
</form>
Here is the jquery file
$(document).ready(function () {
//global vars
var form = $("#step-three");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var contact = $("#contact");
var contactInfo = $("#contactInfo");
var skype = $("#skype");
var skypeInfo = $("#skypeInfo");
var message = $("#message");
//On blur
name.blur(validateName);
email.blur(validateEmail);
contact.blur(validateContact);
skype.blur(validateSkype);
message.blur(validateMessage);
//On key press
name.keyup(validateName);
email.keyup(validateEmail);
contact.keyup(validateContact);
skype.keyup(validateSkype);
message.keyup(validateMessage);
//On Submitting
form.submit(function () {
if (validateName() & validateEmail() & validateContact() & validateSkype() & validateMessage())
return true;
else
return false;
});
//validation functions
function validateEmail() {
//testing regular expression
var a = $("#email").val();
var filter = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//if it's valid email
if (email.val().length == 0) {
email.addClass("error");
emailInfo.text("Required");
emailInfo.addClass("error");
return false;
} else if (filter.test(a)) {
email.removeClass("error");
emailInfo.text("");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else if (!filter.test(a)) {
email.addClass("error");
emailInfo.text("Valid Email Please");
emailInfo.addClass("error");
return false;
}
}
function validateName() {
//if it's NOT valid
if (name.val().length == 0) {
name.addClass("error");
nameInfo.text("Required");
nameInfo.addClass("error");
return false;
}
//if it's valid
else {
name.removeClass("error");
nameInfo.text("");
nameInfo.removeClass("error");
return true;
}
}
function validateContact() {
//if it's NOT valid
if (contact.val().length == 0) {
contact.addClass("error");
contactInfo.text("Required");
contactInfo.addClass("error");
return false;
}
//if it's valid
else {
contact.removeClass("error");
contactInfo.text("");
contactInfo.removeClass("error");
return true;
}
}
function validateSkype() {
//if it's NOT valid
if (skype.val().length == 0) {
skype.addClass("error");
skypeInfo.text("Required");
skypeInfo.addClass("error");
return false;
}
//if it's valid
else {
skype.removeClass("error");
skypeInfo.text("");
skypeInfo.removeClass("error");
return true;
}
}
/* function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}*/
function validateMessage() {
//it's NOT valid
if (message.val().length < 10) {
message.addClass("error");
messageInfo.text("More than 10 Characters required");
messageInfo.addClass("error");
return false;
}
if (message.val().length == 0) {
message.addClass("error");
messageInfo.text("Required");
messageInfo.addClass("error");
return false;
}
//it's valid
else {
message.removeClass("error");
messageInfo.text("");
messageInfo.removeClass("error");
return true;
}
}
});
You have to use preventDefault() function. The submit function can't be 'canceled' with returning false. it is an event and there are many handlers 'listening' to it. You have to stop the event from propagating, thus preventing the handlers to handle the event ;)
The code:
$("form").submit(function(e){
if(!(validateName() && validateEmail() && validateContact() && validateSkype() && validateMessage())){
e.preventDefault();
// and maybe some alert() with fail info
}
else{
//whatever you need if validation suceeds
}
});
use && place of &
I hope it will help

Create and send an e-mail from a form + keep javascript filters

On the contact page, I do have a form that will allow users to send e-mails to the company. To control each field, I had a script to the form and some css effects.
This is working perfectly.
Here is a DEMO (Sadly, it can't work on jsfidle)
However, I didn't find any solution to send an e-mail with javascript (impossible). But what do I have to do to keep my javascript functionalities and send this e-mail?
Note: After sending the e-mail,the user has to stay on the same page.
HTML
<form onSubmit="return formValidation();" id="contactForm" name="contactForm" action="index.php">
<ul>
<label for="name">Name <span id="required">*</span></label>
<li><input name="name" id="name" type="text"/></li>
</ul>
<ul>
<label for="telephone">Telephone <span id="required">*</span></label>
<li><input name="telephone" id="telephone" type="text"/></li>
</ul>
<ul>
<label for="email">Email <span id="required">*</span></label>
<li><input name="email" id="email" type="text"></li>
</ul>
<ul>
<label for="message">Message <span id="required">*</span></label>
<li><textarea name="message" id="message" cols="70" rows="10" ></textarea></li>
</ul>
<ul id="row_submit_button">
<li><input type="submit" value="Submit" id="submit_button"/></li>
</ul>
<ul id="form_incorect_message">
<li>Please, fill in the form correctly.</li>
</ul>
</form>
Javascript
function formValidation()
{
var name = document.contactForm.name; // required
var telephone = document.contactForm.telephone; // required
var email = document.contactForm.email; // required
var message = document.contactForm.message; // required
fname_validation(name);
number_validation(telephone);
email_validation(email);
message_validation(message);
if (fname_validation(name)&&number_validation(telephone)&&email_validation(email)&&message_validation(message))
{
document.getElementById('form_incorect_message').style.visibility = 'hidden';
document.getElementById('contactForm').style.visibility = 'hidden';
document.getElementById('send_ok').style.display = 'block';
// sendMail();
}
else
{
}
return false;
};
function fname_validation(name)
{
if((name.value!="")&&(name.value!=" "))
{
var letters = /^[A-Za-z _-]+$/;
if(name.value.match(letters))
{
document.getElementById('name').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('name').style.borderColor = "red";
return false;
}
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('name').style.borderColor = "red";
return false;
}
};
function message_validation(message)
{
if(message!=""&&message!=" ")
{
var letters = /^[A-Za-z0-9 _-]+$/;
if(message.value.match(letters))
{
document.getElementById('message').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('message').style.borderColor = "red";
return false;
}
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('message').style.borderColor = "red";
return false;
}
};
function number_validation(telephone)
{
var numbers = /^[0-9+]+$/;
if(telephone.value.match(numbers))
{
document.getElementById('telephone').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('telephone').style.borderColor = "red";
return false;
}
};
function email_validation(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.match(mailformat))
{
document.getElementById('email').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('email').style.borderColor = "red";
return false;
}
};
function sendMail()
{
// var link = "mailto:my-email#gmail.com"
// + "?cc=xxxxxxx#xXXXXX.co.uk"
// + "&subject=" + escape("This is my subject")
// + "&body=" + escape(document.getElementById('myText').value);
// window.location.href = link;
};
Thanks

Categories