Mail not sending after valiidation - php

this is an expanded version of a question I asked last night, but with much more detail. All my php files and js file are in a folder called js one level down from my html pages.
I have a contact form that mails the content of my shopping cart and form inputs to my email using php mail. I am validating the form on submit:
<form name="theForm" id="theForm" onsubmit="return validateFormOnSubmit(this)">
with this submit button:
<input type=submit name=Submit value=Send style=cursor:pointer/>
The validation works as it should, here is the code (validate.js):
function setSelRange(inputEl, selStart, selEnd) {
if (inputEl.setSelectionRange) {
inputEl.focus();
inputEl.setSelectionRange(selStart, selEnd);
} else if (inputEl.createtextRange) {
var range = inputEl.createtextRange();
range.collapse(true);
range.moveEnd('character', selEnd);
range.moveStart('character', selStart);
range.select();
}
}
window.onload=function(){
setSelRange(document.theForm.textbox, 0, 0);
}
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateName(theForm.name);
reason += validatePhone(theForm.phone);
reason += validateEmail(theForm.emaile);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
simpleCart.checkout()
}
function validateEmpty(fld) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = '#3399ff';
error = "The required field has not been filled in.\n"
} else {
fld.style.background = 'White';
}
return error;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateName(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (fld.value == "") {
fld.style.background = '#3399ff';
error = "Please enter a name.\n";
} else if ((fld.value.length < 2) || (fld.value.length > 30)) {
fld.style.background = '#3399ff';
error = "The nme is too long!\n";
} else {
fld.style.background = 'White';
}
return error;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(fld) {
var error="";
var tfld = trim(fld.value); // valu
trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (fld.value == "") {
fld.style.background = '#3399ff';
error = "Please enter an email address.\n";
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
fld.style.background = '#3399ff';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = '#3399ff';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');
if (fld.value == "") {
error = "Please enter a phone number.\n";
fld.style.background = '#3399ff';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number can only contain numbers.\n";
fld.style.background = '#3399ff';
} else if (!(stripped.length == 10)) {
error = "The phone number is the wrong length. area code.\n";
fld.style.background = '#3399ff';
}
return error;
}
I am tring to then run the function simpleCart.checkout() when the form successfully validates: (from the above code)
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
simpleCart.checkout()
}
here is the function from simpleCart.js I am tring to call, (set to emailCheckout):
me.checkout = function() {
if( me.quantity === 0 ){
error("Cart is empty");
return;
}
switch( me.checkoutTo ){
case PayPal:
me.paypalCheckout();
break;
case GoogleCheckout:
me.googleCheckout();
break;
case Email:
me.emailCheckout();
break;
default:
me.customCheckout();
break;
}
};
me.emailCheckout = function() {
itemsString = "";
for( var current in me.items ){
var item = me.items[current];
itemsString += item.name + " " + item.quantity + " " + item.price + "\n";
}
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "js/sendjs.php";
form.acceptCharset = "utf-8";
form.appendChild(me.createHiddenElement("wsp_key", wsp_key));
form.appendChild(me.createHiddenElement("wsp_code", wsp_code));
form.appendChild(me.createHiddenElement("textbox", textbox));
form.appendChild(me.createHiddenElement("name",name));
form.appendChild(me.createHiddenElement("phone",phone));
form.appendChild(me.createHiddenElement("emaile",emaile));
form.appendChild(me.createHiddenElement("jcitems", itemsString));
form.appendChild(me.createHiddenElement("jctotal", me.total));
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
It recieves the cart info, inputs and captcha key and code from the form and actions sendjs.php to mail it to me:
(from the code above)
form.action = "js/sendjs.php";
If the captcha code is correct it will mail it to me and redirect to "from-accepted.php" page, if not it will redirect to a "form-rejected.php" page (sendjs.php):
<?php
include_once("wsp_captcha.php");
if(WSP_CheckImageCode() != "OK") {
header('location:/form-rejected.php');
die();
}
$to = 'diysoakwells#hotmail.com';
$subject = 'Order Inquiry';
$jcitems = " <p><b>ORDER:</b></p><p> " . $_POST['jcitems']."<p/>" . "<p><b>Total:</b> $" . $_POST['jctotal']."</p>";
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= 'From: inquiry#diysoakwells.com' . "\r\n" .
'Reply-To: noreply#diysoakwells.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$name = $_POST['name'];
$phone = $_POST['phone'];
$emaile = $_POST['emaile'];
$textbox = $_POST['textbox'];
$text = "<html><body><p>This form was submitted on Your Web Site on \n $date at\n $time</p><p><b>Message:</b>\n$textbox</p><p><b>Customers Email Address:</b>$emaile</p><p><b>Customers Name:</b> $name </p><p><b>Customers Phone Number:</b> $phone </p></html></body>";
$body = $text . $jcitems;
mail($to, $subject, $body, $headers);
Header('Location: ../form-accepted.php');
?>
The problem is that after validation is doesn't action sendjs.php and just reloads the contact page. Debugger is showing no error and I have tested simpleCart.checkout by other means and it should work. Sorry for the length of this post but I am stumped and am losing business (and a lot of sleep trying to get it to work) not having this form functioning.
here is a link to the page:
http://www.diysoakwells.com.au/cart.php
Does anyone have any suggestions? I have to pop out now for an hour but I will be monitoring this post and when I return, working on the problem for at least the next four or five hours or until its fixed. Thanks in advance.
Jamie

In Chrome I got this error: Uncaught TypeError: Cannot read property 'textbox' of undefined on validate.js:16
and BTW I got redirected to http://www.diysoakwells.com.au/form-rejected.php, so the post was ok it seems. Previously it didn't work because my cart was empty

Related

PHP mail with AJAX won't return validation errors form server

I am trying to send an email with PHP and AJAX, and it finally works, but it won't display validation errors returned from the server. I guess I'm doing something wrong in iterating through that data, or just don't understand something with connecting PHP and jQuery with JSON.
PHP mail script on server:
$to = "mymail#gmail.com";
if (isset($_POST['name'], $_POST['mail'], $_POST['text'])) {
if (empty($_POST['name'])) {
$errors[] = "Molimo unesite Vaše ime";
} else {
$contact_name = htmlentities($_POST['name']);
}
if (empty($_POST['mail'])) {
$errors[] = "Molimo unesite Vašu email adresu.";
} else if (strlen($_POST['mail']) > 60) {
$errors[] = "Vaša email adresa je predugačka.";
} else if (filter_var($_POST['mail'], FILTER_VALIDATE_EMAIL) === false ) {
$errors[] = "Unesite validnu email adresu.";
} else {
$contact_mail = "<" . htmlentities($_POST['mail']) . ">";
}
if (empty($_POST['text'])) {
$errors[] = "Molimo unesite poruku.";
} else {
$contact_text = htmlentities($_POST['text']);
}
}
if (empty($errors) === true) {
if(isset($contact_text, $contact_name, $contact_mail)) {
$subject = "Mail from " . $contact_name ." via www.mysite.com";
$headers = "From: " . $contact_mail;
$sent = mail($to, $subject, $contact_text, $headers);
if ($sent) {
die("true");
} else {
return json_encode($errors);
}
}
}
Relevant jQuery:
var mailBroker = {
send : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
if (contact_name === "" || contact_mail === "" || contact_text === "") {
//form not complete
} else {
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
} else {
var parsedData = $.parseJSON(data);
$.each(parsedData, function() {
var that = $(this);
setStatus(that);
});
}
});
}
},
setStatus : function(status) {
$('textarea[name="contact-text"]').after('<span>' + status + '</span>');
}
}
And inside $(document).ready():
$('#contact-us form').submit(function(event) {
event.preventDefault();
mailBroker.send();
$(this).trigger('reset');
});
Can somebody point out what I am doing wrong?
Of course, I know that I could just do it on the client-side, but that it is bad practice. So I left that part out for now and assumed that invalid or no data got through for required form fields.
Answer form is easier to explain this. The logic in your code never gives your script a chance to output the errors to the AJAX. You'd need to change the logic so it will. Ie.
if (empty($errors) === true) {
if(isset($contact_text, $contact_name, $contact_mail)) {
$subject = "Mail from " . $contact_name ." via www.mysite.com";
$headers = "From: " . $contact_mail;
$sent = mail($to, $subject, $contact_text, $headers);
if ($sent) {
die("true");
} else {
die("false"); // with json_encode here, $errors will always be empty
}
}
} else {
die(json_encode($errors)); //$errors wasn't empty, this is where you need to hand it back to the JS.
}
This is why firebug or another tool would help. You'd see that the information you were wanting given to your JS wasn't there - that way you know to look at the PHP (server-side) since it isn't outputting as expected. If it was, you'd check in to the JS code to see why that isn't processing it as expected.
EDIT: Your javascript doesn't allow the PHP to execute when a field is empty, but you are wanting the feedback PHP will give if one is empty, so you'd want to change your JS to something like:
var mailBroker = {
send : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
} else {
var parsedData = $.parseJSON(data);
$.each(parsedData, function() {
var that = $(this);
setStatus(that);
});
}
});
},
setStatus : function(status) {
$('textarea[name="contact-text"]').after('<span>' + status + '</span>');
}
}
A little modification of Jon's answer because you will still need to extract the messages from the returned JSON:
var mailBroker = {
'send' : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
$('#contact-us form').trigger('reset');
} else { //validation failed
var parsedData = $.parseJSON(data);
var msg = '';
$.each(parsedData, function() {
var that = $(this);
for (var i = 0; i < that.size(); i++) {
msg += that[i];
}
mailBroker.setStatus(msg); //msg used to be 'that'
msg = '';
});
}
});
},
'setStatus' : function(status) {
$('#validation-msgs').prepend('<p class="validation-msg">' + status + '</p>');
}
}
Essentially - you will need to pass through parsed data to get each of the messages. The problem is that they are also stored as arrays - of characters. So you will need to pass through those, too, and append those characters to a message String.
Then, you should prepend those messages to some container for warnings so they are in the right order. If you don't do that, you will get [Object] instead of the message text.
Hope this helps.
Hi I think you messed up on your line 3 mail script.
if (isset($_POST['name'], $_POST['mail'], $_POST['text'])) {
because you will use comparison operators for that.
Like this below.
if (isset($_POST['name'] && $_POST['mail'] && $_POST['text'])) {

JQuery Ajax Post to MailForm.php

I want to go directly to my problem: My application shows data from an mysql database and the user can select those items and save them into an javascript list. After he has selected his items we want that he write his name in an inputfield and with the click on an button the "javascript-list" (contains only strings) should be send to our mailForm.php via post & ajax.
The problem is that our mailForm.php works perfectly fine (trying to access via Java and sending Post data) but we are not able to post the data via ajax and javascript (have a look:)
mailForm.php
<?
if ($_POST) {
$message = "";
while (list ($key, $val) = each ($_POST)) {
if ($key == "mailAn") {
$mymail = $val;
} elseif ($key == "subject") {
$subject = $val;
} elseif ($key == "mailVon") {
$email = $val;
} elseif ($key == "message") {
$message = $val;
}
}
//array_walk ($_POST, "GetValues");
if (mail($mymail,$subject,$message,"From: $email")) {
header ("");
} else {
header ("Location: form_notok.htm");
//echo "Fehler beim Senden des Formulars!";
}
}
?>
As you can see wie have 4 keys (mailAn, subject, mailVon, message).. Any idea how this goes via js/jquery? (getting the Strings (javascriptlist) as message and the name (from inputfield) into mailVon)
Javascript:
$("#contact").submit(function(e){
e.preventDefault();
var name = $("#name").val(); //Inputfield with Name
var email = $("#email").val(); // Inputfield with email
var text = $("#text").val(); //should be list
var dataString = 'mailVon=' + name + '&mailAn=' + email + '&message=' + text;
$.ajax({
type: "POST",
url: "./mailForm.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
return false;
});
EDIT:
I now added the subject post param:
var dataString = 'mailVon=' + name + '&subject' + 'Test via javascript' + '&mailAn=' + email + '&message=' + text;
I still get an success message but no mail...
I would setup some echos and debug it with firebug.
if (isset($_POST['mailAn'])){
echo "Phase 1";
foreach($_POST as $key => $value)
{
switch ($key){
case "mailAn":
$mymail = $value;
echo "Phase 2";
break;
}
}
}else{
echo "FAILED";
}
I would add headers to the mail function.
`
<?
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: ' . $to . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$headers .= 'Cc: ' . "\r\n";
$headers .= 'Bcc: ' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
`
The code above works perfectly fine - problem was the settings of the test host we used. Using our business webspace it will work. Good Look.
MailForm.php
<?
if ($_POST) {
$message = "";
while (list ($key, $val) = each ($_POST)) {
if ($key == "mailAn") {
$mymail = $val;
} elseif ($key == "subject") {
$subject = $val;
} elseif ($key == "mailVon") {
$email = $val;
} elseif ($key == "message") {
$message = $val;
}
}
//array_walk ($_POST, "GetValues");
if (mail($mymail,$subject,$message,"From: $email")) {
header ("");
} else {
header ("Location: form_notok.htm");
//echo "Fehler beim Senden des Formulars!";
}
}
?>
JavaScript with fixed mail & javascript-list as dataString:
// Contact Form
$("#contact").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = 'your#email.com';
var message = '';
for (var i = 0; i < musicList.length; i++) {
message += musicList[i];
if(i < (musicList.lenght-1)){
message += ', ';
}
}
var dataString = 'mailVon=' + name + '&subject=' + 'Betreff: Music' + '&mailAn=' + email + '&message=' + message;
$.ajax({
type: "POST",
url: "./mailForm.php",
data: dataString,
success: function(data) {
if(data.status == 'success')
$('.success').fadeIn(1000);
else if(data.status == 'error')
$('.error').fadeIn(1000);
}
});
return false;
});
Hope it will help someone else too
-Domi

php echo keeps opening in new tab, not in jquery notification toastr.js

I cannot seem to find the problem in my code. I want the validation in php file to trigger the jquery notification plugin 'toastr', however, the php echo keeps publishing the php file message status to a new tab, instead. What am I doing wrong and how can I make the message appear in the notification, instead? The live version of my school site is here: Wright State University BMES Site and the problem can be replicated when submitting the Contact Us form. Thank you in advance :)
HTML:
<form action=send-contact.php method=post data-show-errors="true" class=contact-form id=contact-form-id data-parsley-validate>
<p class=half>
<input autofocus parsley-trigger="change" name=name required id=name placeholder="Type your name" class="testBox label_better" data-new-placeholder="Example: Sir Humphrey Charleston III" parsley-required="true">
</p>
<p class=half>
<input name=email id=email placeholder="Type your e-mail address" class="testBox label_better" data-new-placeholder="Example: humphrey.charleston#wright.edu" parsley-type="email" parsley-trigger="change" required parsley-required="true">
</p>
<p>
<select class="contactselect required" name=subject id=subject parsely-required="true" required parsley-trigger="change">
<option value="" parsley-trigger="change">Please select one topic:</option>
<option value="1" parsley-trigger="change">Information about BMES Chapter</option>
<option value="2" parsley-trigger="change">Information about upcoming events</option>
<option value="3" parsley-trigger="change">Other</option>
</select>
</p>
<p>
<textarea name=message id=message rows=12 cols=20 class="label_better_text" placeholder="Tell us what's on your mind." parsley-trigger="keyup" parsley-rangelength="[1,300]" required parsley-required="true"></textarea>
</p>
<p>
<button name=send type=submit onclick="$( '#contact-form-id' ).parsley('validate')" id=submit value=1>Send message</button>
<span class="color-red"><button onclick="$( '#contact-form-id' ).parsley( 'destroy' ); $('#contact-form-id').parsley();" name=reset type=reset value=1>Reset</button></span>
</p>
</form>
<script type=text/javascript>
jQuery(document).ready(function(c){
$('#contact-form').parsley();
$('#contact-form-id').submit(function(e) {
e.preventDefault();
if ( $(this).parsley('validate') ) {
$.post("send-contact.php", $(this).serialize());
toastr.success('Thank you, we will attend to your message shortly.');
$( '#contact-form-id' ).parsley( 'destroy' );
}
}); });
</script>
PHP:
<?php
$name = '';
$subject = '';
$email = '';
$message = '';
function getIp()
{if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip_address=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
if (!isset($ip_address)){
if (isset($_SERVER['REMOTE_ADDR']))
$ip_address=$_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
//taking the data from form
$name = addslashes(trim($_POST['name']));
$subject = addslashes(trim($_POST['subject']));
$email = addslashes(trim($_POST['email']));
$message = addslashes(trim($_POST['message']));
//form validation
$errors = array();
$fields = array();
if(!$name) {
$errors[] = "Please enter your name.";
$fields[] = "name";
}
$email_pattern = "/^[a-zA-Z0-9][a-zA-Z0-9\.-_]+\#([a-zA-Z0-9_-]+\.)+[a-zA-Z]+$/";
if(!$email) {
$errors[] = "Please enter your e-mail address.";
$fields[] = "email";
} else if(!preg_match($email_pattern, $email)) {
$errors[] = "The e-mail address you provided is invalid.";
$fields[] = "email";
}
if(!$subject) {
$errors[] = "Please choose the subject of your message.";
$fields[] = "subject";
}
if(!$message) {
$errors[] = "Please enter your message.";
$fields[] = "message";
}
//preparing mail
if(!$errors) {
//taking info about date, IP and user agent
$timestamp = date("Y-m-d H:i:s");
$ip = getIp();
$host = gethostbyaddr($ip);
$user_agent = $_SERVER["HTTP_USER_AGENT"];
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\n";
$headers .= "From: $email\n";
$content = 'Subject: '.$subject.'<br>'.
'Name: '.$name.'<br>'.
'E-mail: '.$email.'<br>'.
'Message: '.$message.'<br>'.
'Time: '.$timestamp.'<br>'.
'IP: '.$host.'<br>'.
'User agent: '.$user_agent;
//sending mail
$ok = mail("my-email-address-normally-goes-here","BMES Website Contact Us ", $content, $headers);
if($ok) {
$response['msgStatus'] = "ok";
$response['message'] = "Thank you for contacting us. We will attend to your inquiry as soon as possible.";
} else {
$response['msgStatus'] = "error";
$response['message'] = "An error occured while trying to send your message. Please try again.";
}
} else {
$response['msgStatus'] = "error";
$response['errors'] = $errors;
$response['errorFields'] = $fields;
}
header('Content-type: application/json');
echo json_encode($response);
?>
Javascript:
$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();
button.click(function(e){
e.preventDefault();
var formTop = form.offset().top;
var url = form.attr("action");
var data = form.serialize();
form.find("input, select, textarea, span").removeClass("error");
form.find(".msg").remove();
button.html("Sending...");
$.post(url, data, function(response){
var status = response.msgStatus;
var msg = response.message;
if(status == "ok") {
form.prepend('<p class="msg success"><a class="hide" href="#">hide this</a>' + msg + '</p>');
form.find("input, select, textarea").val("");
var valField = form.find(".select .value");
var selectField = valField.siblings("select");
var selectedText = selectField.find("option").eq(0).html();
valField.html(selectedText);
} else if(status == "error") {
if(response.errorFields.length) {
var fields = response.errorFields;
for (i = 0; i < fields.length; i++) {
form.find("#" + fields[i]).addClass("error");
form.find("select#" + fields[i]).parents(".select").addClass("error");
}
var errors = response.errors;
var errorList = "<ul>";
for (i = 0; i < errors.length; i++) {
errorList += "<li>" + errors[i] + "</li>";
}
errorList += "</ul>";
form.prepend('<div class="msg error"><a class="hide" href="#">hide this</a><p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p></div>');
} else form.prepend('<p class="msg error"><a class="hide" href="#">hide this</a>' + msg + '</p>');
}
$(".msg a.hide").click(function(e){
e.preventDefault();
$(this).parent().slideUp();
});
button.html(buttonText);
window.scrollTo(0, formTop);
}, 'json');
})
});
Have you tried playing with your jquery a bit more? for instance, ajax instead of post.
something like this?
button.click(function () {
$.ajax({
url: url,
type: 'POST',
data: form.serialize(),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.msgSTatus == "ok"){
alert(data.message);
// play with html here once you know the page stays.
}
},
error: function (data) {
alert('Fail.');
}
});
});
As far as html appending goes, I would personally have an empty on the page already with an id, and just set the content of the div to the data that you receive, would make the js look much cleaner maybe..
Try including jquery before your other scripts. Also, use Firebug or build-in browser JS debugging tools to troubleshoot Javascript errors.
I have managed to solve the issue. Alterations are listed below for comparative purposes to not only help others but to also close this issue. A special thank you to #WhiteRuski for pointing me in the right direction. The PHP and HTML remain unchanged. Here is the new Javascript:
$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();
button.click(function(e){
e.preventDefault();
var url = form.attr("action");
var data = form.serialize();
// button.html("Sending...");
button.html('<i class="fa fa-cog fa-lg fa-spin"></i>' + ' Sending ... ');
$.post(url, data, function(response){
var status = response.msgStatus;
var msg = response.message;
if(status == "ok") {
toastr.success('<p>' + msg + '</p>');
var valField = form.find(".select .value");
var selectField = valField.siblings("select");
var selectedText = selectField.find("option").eq(0).html();
valField.html(selectedText);
} else if(status == "error") {
if(response.errorFields.length) {
var fields = response.errorFields;
for (i = 0; i < fields.length; i++) {
form.find("#" + fields[i]).addClass("error");
form.find("select#" + fields[i]).parents(".select").addClass("error");
}
var errors = response.errors;
var errorList = "<ul>";
for (i = 0; i < errors.length; i++) {
errorList += "<li>" + errors[i] + "</li>";
}
errorList += "</ul>";
// toastr.error('<p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p>'); This lists the specific errpr in the field
toastr.error('<p>There were a few errors in your form. Please resubmit with corrections.</p>');
} else toastr.error('<p>' + msg + '</p>');
}
button.html(buttonText);
}, 'json');
})
});

Ajax contact form is not sending an email

I'm using ajax contact form:
jQuery(document).ready(function () {
// Comment or uncomment the result you want.
// Currently, shake on error is enabled.
// When a field is left blank, jQuery will shake the form
/* Begin config */
// var shake = "Yes";
var shake = "No";
/* End config */
$('#message').hide();
// Add validation parts
$('#contact input[type=text], #contact input[type=number], #contact input[type=email], #contact input[type=url], #contact input[type=tel], #contact select, #contact textarea').each(function () {
$(this).after('<mark class="validate"></mark>');
});
// Validate as you type
$('#email').focusout(function () {
if (!$(this).val() || !isEmail($(this).val())) $(this).addClass('error').parent().find('mark').removeClass('valid').addClass('error');
else $(this).removeClass('error').parent().find('mark').removeClass('error').addClass('valid');
});
$('#submits').click(function () {
$("#message").slideUp(200, function () {
$('#message').hide();
// Kick in Validation
$('#email').triggerHandler("focusout");
if ($('#contact mark.error').size() > 0) {
if (shake == "Yes") {
$('#contact').effect('shake', {
times: 2
}, 75, function () {
$('#contact input.error:first, #contact textarea.error:first').focus();
});
} else $('#contact input.error:first, #contact textarea.error:first').focus();
return false;
}
});
});
$('#contactform').submit(function () {
if ($('#contact mark.error').size() > 0) {
if (shake == "Yes") {
$('#contact').effect('shake', {
times: 2
}, 75);
}
return false;
}
var action = $(this).attr('action');
$('#submits')
.after('<img src="/system/cms/themes/default/views/partials/assets/ajax-loader.gif" class="loader" />')
.attr('disabled', 'disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
website: $('#website').val(),
kvk: $('#kvk').val(),
sending: $('#sending').val(),
webwinkel: $('#webwinkel').val(),
pakketten: $('#pakketten').val(),
},
function (data) {
$('#message').html(data);
$('#message').slideDown();
$('#contactform img.loader').fadeOut('slow', function () {
$(this).remove()
});
$('#contactform #submits').attr('disabled', '');
if (data.match('success') != null) $('#contactform').slideUp('slow');
});
return false;
});
function isEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
function isNumeric(input) {
return (input - 0) == input && input.length > 0;
}
});
In some way it is not sending the email if i exclude this script the email script does work?
Ive tried everything but i can't get it to work , i think its strange because im using this script on more places and there its working :(...
anyone idea's ?
* Update Mail script *
<?php if (!isset($_SESSION)) session_start();
if(!$_POST) exit();
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$website = $_POST['website'];
$kvk = $_POST['kvk'];
$sending = $_POST['sending'];
$webwinkel = $_POST['webwinkel'];
$pakketten = $_POST['pakketten'];
$error = '';
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
// Important Variables
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
$address = "email#email.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'Nieuwe Aanmelding';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "Er is een nieuwe aanmelding binnen gekomen:\n\n" . PHP_EOL . PHP_EOL;
$e_name = "Name: $name \n\n";
$e_email = "Email: $email \n\n";
$e_phone = "Tel: $phone \n\n";
$e_kvk = "KVK: $kvk \n\n";
$e_website = "Website: $website \n\n";
$e_sending = "Verzending nu: $sending \n\n";
$e_winkel= "Webwinkel: $webwinkel \n\n";
$e_pakketten= "Paketten per maand: $pakketten \n \n";
$msg = wordwrap($e_body . $e_name . $e_email . $e_website . $e_phone . $e_kvk . $e_sending . $e_winkel . $e_pakketten,70);
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<div class='span12'>";
echo "<div class='span4'></div>";
echo "<div class='span6'>";
echo "<div id='success_page'>";
echo "<h1 style='color:white'>Uw aanmelding is verzonden.</h1>";
echo "<p style='color:white'>Bedankt <strong>$name</strong>, U wordt zo spoedig mogelijk geholpen.</p>";
echo "</div>";
echo "</div>";
} else {
echo 'ERROR!';
}
}
?>
Resolved
Guys,
Thanks for the quick response.
This is the new jquery ive just downloaded and its working now.
$('#contactform').submit(function(){
if ($('#contact mark.error').size()>0) {
if(shake == "Yes") {
$('#contact').effect('shake', { times:2 }, 75);
}
return false;
}
var action = $(this).attr('action');
$('#submit')
.after('<img src="assets/img/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, $('#contactform').serialize(),
function(data){
$('#message').html( data );
$('#message').slideDown();
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#contactform #submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
return false;
});
There's so much wrong on so many levels, please first take a look at www.phptherightway.com.
After that, try and figure out if the form is being sent to the server (via the POST request method). If it's not, I'm guessing the form is returning false on the submit event, and that'll be the reason it's not working most likely.

I can't get my form to validate AND submit using jQuery validation

I have been digging around on here and other sites for a while and am stuck. I'm trying to use jQuery to validate my form (concurrently as the user fills out the form) and, if the form is valid have it submit to a php page I have created to process the contents of the form. I have been able to have it validate but I can't have it also submit it...if I put a value in for the form action parm then it bypasses the validation. Please help...
I apologize, in advance, for the bad coding.
Here is my jquery-validate.js:
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.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");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
name.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage())
return true;
else
return false;
});
My form code is pasted here:
<form method="post" id="customForm" action="rcv-form1.php">
<div>
<label for="name">Name</label>
<input id="name" name="name" type="text" />
<span id="nameInfo">What's your name?</span>
</div>
<div>
<label for="email">E-mail</label>
<input id="email" name="email" type="text" />
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</div>
<div>
<label for="pass1">Password</label>
<input id="pass1" name="pass1" type="password" />
<span id="pass1Info">At least 5 characters: letters, numbers and '_'</span>
</div>
<div>
<label for="pass2">Confirm Password</label>
<input id="pass2" name="pass2" type="password" />
<span id="pass2Info">Confirm password</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="" rows=""></textarea>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</form>
And here is my php that receives the form (this is just for testing now. i will email or insert into mySQL once i know i can properly validate stuff):
<html><head>
<title>Display form values</title>
</head>
<body>
<?
//$valid_form = TRUE;
//$bad_field_count = 0;
$table1_beg = '<center><table align="center" bordercolor="#F00" width="600px" border="3" cellspacing="1" cellpadding="1"><caption>Form status</caption><tr><th scope="col">Field Name</th><th scope="col">Field Value</th></tr>';
$row_beg = '<tr><td>';
$td = '</td><td>';
$row_end = '</td></tr>';
$table1_end = '</table></center>';
function checkEmail($field)
{
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
//echo "This ($field) email address is considered valid.";
return $field;
} else {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
//global $bad_field_count; $bad_field_count++;
return $field;
}
}
function SanitizeString($field)
{
$field = filter_var($field, FILTER_SANITIZE_STRING);
//if(is_null($field) || $field == '') { global $bad_field_count; $bad_field_count++;}
return $field;
}
// ensure form data is valid
$name=SanitizeString($_POST['name']);
//$email=$_POST['email'];
$email = checkEmail($_POST['email']);
$pass1=SanitizeString($_POST['pass1']);
$pass2=SanitizeString($_POST['pass2']);
$message=SanitizeString($_POST['message']);
echo $table1_beg;
echo $row_beg . "Name" . $td . "<u>" . $name . "</u>" . $row_end;
echo $row_beg . "Email" . $td . "<u>" . $email . "</u>" . $row_end;
echo $row_beg . "Password 1" . $td . "<u>" . $pass1 . "</u>" . $row_end;
echo $row_beg . "Password 2" . $td . "<u>" . $pass2 . "</u>" . $row_end;
echo $row_beg . "Message" . $td . "<u>" . nl2br($message) . "</u>" . $row_end;
//echo $row_beg . "Number of bad fields" . $td . "<b>" . $bad_field_count . "</b>" . $row_end;
echo $table1_end;
//}
?>
</body></html>
Problem 1: When I have form action="" I can validate the form only after hitting submit...it doesn't say it's invalid until after submitting when I thought it should do it concurrently as it is typed in.
Problem 2: If I have my form action set to anything but "" it will ignore the jQuery validation all together.
I'm new to the form validation stuff. Can someone point me in the right direction? Thanks, in advance!
You have a few problems, your form submit code doesn't have curly brackets around it, and you don't have a function for validate email, try this:
//global vars
var form = $("#customForm");
var fname = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
function validateName() {
//if it's NOT valid
if (fname.val().length < 4) {
fname.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else {
fname.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
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 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 validateMessage() {
//it's NOT valid
if (message.val().length < 10) {
message.addClass("error");
return false;
}
//it's valid
else {
message.removeClass("error");
return true;
}
}
function validateEmail(){
//add validation for email here
return true;
}
/*
Validate the name field in: blur and keyup events.
Validate the email field in: blur event.
Validate the password fields in: blur and keyup events.
Validate the message field in: blur, and keyup event.
Validate all fields in: submit form event
*/
//On blur
fname.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
fname.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function() {
if (validateName() && validateEmail() && validatePass1() && validatePass2() && validateMessage()) {
return true;
}
else {
return false;
}
});
I've gave you an easy way to validate your all inputs/textarea within one function but you have to complete it, I've just gave you the structure and only name validation has done as an example for you and I hope you can understand it easily. If you need more help/difficulties just leave a message. This should be placed inside ready event.
var info={
'nameInfo':$("#nameInfo"),
'emailInfo':$("#emailInfo"),
'pass1Info':$("#pass1Info"),
'pass2Info':$("#pass2Info")
}
$('#customForm input,textarea').not("#send").bind('blur keyup', function(e)
{
e.stopPropagation();
var el=$(e.target);
var id=el.attr('id');
if(el.attr('id')=='message' && e.type=="keyup")
{
return false;
}
else
{
if(id=="name")
{ if(el.val().length < 4)
{
el.addClass("error");
info.nameInfo.text("We want names with more than 3 letters!");
info.nameInfo.addClass("error");
return false;
}
else
{
el.removeClass("error");
info.nameInfo.text("What's your name ?");
info.nameInfo.removeClass("error");
return true;
}
}
if(id=="email")
{
// Your email validation code
}
if(id=="pass1")
{
// Your pass1 validation code
}
if(id=="pass2")
{
// Your pass2 validation code
}
if(id=="message")
{
// Your message validation code
}
}
});

Categories