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
Related
Here is textboxes I am trying to send with email.
Please help me with the code.The textboxes are dynamic
HTML
Flavor<input class="textbox" type='text' id="fl" name="flav[]" value=""/></label></br>
AJAX
<script type="text/javascript">
$(document).ready(function() {
$("#submit_btn").click(function() {
var str = new Array();
$("input[name='flav[]']").each(function(){
str.push($(this).val());
});
alert(str);
var proceed = true;
if(str==""){
$('input[name=flav]').css('border-color', 'red');
proceed = false;
}
if(proceed)
{
//data to be sent to server
post_data={'userData':str};
$.post('mail.php', post_data, function(response){
//load JSON data from server and output message
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$('#contact_form input').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input").keyup(function() {
$("#contact_form input").css('border-color', '');
$("#result").slideUp();
});
});
</script>
PHP
<?php
if($_POST)
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting JSON data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(!isset($_POST["userData"]))
{
}
foreach($_POST as $key=> $value)
{
$message .= $key .":".$value."<br>";
}
$headers = "From: " . $user_Email . "\r\n";
$headers .= "Reply-To: ". $user_Email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$sentMail = #mail($to_Email, $subject, $message, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email'));
die($output);
}
}
?>
Kindly help me with this.
How can I recieve all the values entered via message?
I have edited the code
Looks like you will get text with 'Array' in it, to fix it change
foreach($_POST as $key=> $value)
{
$message .= $key .":".$value."<br>";
}
to
foreach($_POST[userData] as $key=> $value)
{
$message .= $key .":".$value."<br>";
}
(This will only work one level down in your array) or replace it with:
$message = print_r($_POST, true);
from Store print_r result into a variable as a string or text to show the full depth of the array
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');
})
});
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.
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
I'm using jQuery's AJAX function to send a message from a contact form -
$('form button').click(function () {
$("input").removeClass("error");
$("textarea").removeClass("error");
var name = $("#name").val();
if (name == "" || name == "Name" || name == "Namn") {
$("#name").addClass("error");
$("#name").focus();
return false;
}
var email = $("#email").val();
if (email == "" || email == "Email" || email == "Epost") {
$("#email").addClass('error');
$("#email").focus();
return false;
}
var message = $("#message").val();
if (message == "") {
$("#message").addClass('error');
$("#message").focus();
return false;
}
// Non-verifying fields
var phone = $("input#phone").val();
// Gather data
var post = 'name=' + name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// Disable form
var limit = document.forms[0].elements.length;
for (i = 0; i < limit; i++) {
document.forms[0].elements[i].disabled = true;
}
// Send data
$.ajax({
type: "POST",
url: "form_handler.php",
data: post,
success: function () {
$('div.contact form').animate({
opacity: 0.25
}, function () {
$('div.contact div.confirm').fadeIn(200);
});
},
error: function () {
$('div.contact form').animate({
opacity: 0.25
}, function () {
$('div.contact div.deny').fadeIn(200);
});
}
});
return false;
});
I know this is not the safest method considering I reveal the Mail file in my JS code but nevertheless I want this to work before I decide to try anything else. In my contact form I have the above fields (name, email, phone and message) and in "form_handler.php" the settings look like this -
<?php
header('Content-type: text/html; charset=UTF-8');
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$to = "staffan.estberg#gmail.com";
$subject = "Meddelande från x.se";
$body = "------------------------------------------------------------------------------------------------------------------------\n\n";
$body .= "Meddelande från $name:\n\n";
$body .= "$message\n\n";
$body .= "Avsändarens epost: $email\n";
$body .= "Avsändarens telefonnummer: $phone\n\n";
$body .= "------------------------------------------------------------------------------------------------------------------------";
$headers = "From: $email";
mail($to,$subject,$body,$headers);
?>
When I combine the scripts I manage to generate a message though it doesn't contain any form data. Have I missed out on something?
I think you'll actually want to pass a JSON array as the data parameter instead of the GET-style string.
Something like:
post = { 'name' : name, ... }