Php code to validate and send form data to an email address
My php wont validate my ajax post call method and have my formdata sent to an email address on submit button click. I am probably missing out some codes and Here is a sample of what my code looks like.
Any answers?
<body>
<div class="tab_content active_tab" id="name">
<form method="post" class="import_form">
<input type="hidden" id="doc_type" name="doc_type" value="" required>
<textarea name="name" placeholder="Name" required></textarea>
<input type="hidden" name="importer1" value="1">
<button type="submit">SEND</button>
</form>
</div>
<div class="tab_content" id="account_type">
<form method="post" class="import_form">
<input type="hidden" id="doc_type" name="doc_type" value="" required>
<textarea name="account_type" placeholder="ACCOUNT TYPE" required></textarea>
<input type="hidden" name="date" placeholder="Date" required>
<input type="hidden" name="importer2" value="1">
<button type="submit">SEND</button>
</form>
</div>
</div>
</div>
<script src="assets/js/jquery.min.html"></script>
<script src="assets/bootstrap/js/bootstrap.min.html"></script>
</body>
<script>
var root_link = "index.html";
forms = document.getElementsByClassName('import_form');
for(let i = 0;i < forms.length; i++){
forms[i].addEventListener('submit',function(e){
e.preventDefault();
data = new FormData(this);
request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//alert(this.responseText);
if(this.responseText == true){
location = 'image.html';
}
}
};
}
function open_tap(tab){
var tabs = document.getElementsByClassName('tab_content');
var tabs_key = document.getElementsByClassName('import_tab');
for(let i = 0; i < tabs.length; i++){
tabs[i].style.display = 'none';
}
for(let i = 0; i < tabs_key.length; i++){
tabs_key[i].style.borderBottom = 'none';
}
document.getElementById(tab).style.display = 'block';
document.getElementsByClassName(tab)[0].style.borderBottom = '1px solid #fff';
}
</script>
<script>
$("#loader").hide();
function loading(t){
$("#loader").show();
setTimeout(function(){
$("#loader").hide();
},t);
}
$('#name').submit(function(e){
e.preventDefault();
var a = $('#name_val').val(),
b = $('#doc_type').val();
$.ajax({
method:"POST",
url:"set.php",
data:{name:a,doc_type:b,importer1:true},
beforeSend:function(){
loading(2500);
},
success:function(r){
loading(5000);
// alert(r);
location = 'image-2.html';
}
});
});
$('#accountype_form').submit(function(e){
e.preventDefault();
var a = $('#accountype_val').val(),
b = $('#doc_type').val(), c = $('#date').val();
$.ajax({
method:"POST",
url:"set.php",
data:{accounttype_val:a,doc_type:b,date:c,importer2:true},
beforeSend:function(){
loading(2500);
},
success:function(r){
loading(5000);
location = 'image-2.html';
}
});
});
</script>
<?php
if(isset($_POST['submit'])){
$to = "anything#domain.com";
$name = $_POST['name'];
$acounttype = $_POST['accounttype'];
$errorMSG = "";
if (empty($_POST["name"])) {
$errorMSG = "location:'image2_html'";
} else {
$name = $_POST["name"];
}
if (empty($_POST["accounttype"])) {
$errorMSG .= "location:'image2_html'";
} else {
$accounttype = $_POST["accounttype"];
}
?>
Related
I want to validate the minlength and maxlength of textarea before submitting, can anyone tell me details?
<form id="contact-je" action="<?php echo JURI::current(); ?>" method="post">
<div class="input">
<label id="je_hide_message" for="message"><?php echo JText::_("$message"); ?></label>
<textarea name="je_message" id="message" class="requiredField" rows="4"
placeholder="<?php echo $message; ?>"><?php if (isset($_POST['je_message'])) {
if (function_exists('stripslashes')) {
echo stripslashes($_POST['je_message']);
} else {
echo $_POST['je_message'];
}
} ?></textarea>
<?php if (!isset($_SESSION)) {
if ($messageError != '') { ?><span
class="error"><?php echo $messageError; ?></span><?php }
} ?>
</div>
<div class="input">
<button name="submit" type="submit"
class="je_button"><?php echo JText::_("$submit") ?></button>
<input type="hidden" name="submitted" id="submitted" value="true"/>
</div>
</form>
<?php } ?>
</div>
If you are allowed to use the browser feature, you can just set minlength and maxlength attributes of <textarea>.
<form>
<textarea minlength="5" maxlength="10"></textarea>
<input type="submit">
</form>
I add following codes, but if enter more than 300characters, the form will still be submitted. I don't want to submit if the characters is over 300
// Validate error
$('form#contact-je').submit(function () {
$('form#contact-je .error').remove();
var hasError = false;
$('.requiredField').each(function () {
if ($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Pls enter ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You\'ve entered an invalid ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
}
}
});
//Limit message characters
$('#message').keyup(function() {
if ($(this).val().length > 300){
$(this).parent().append('<span class="error">ffffff</span>');
$(this).addClass('invalid');
hasError = true;
}
});
if (!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('form#contact-je').slideUp("fast", function () {
$(this).before('<span class="success"><strong>Thank you!</strong> We have received your email.<br />We will get back to you in 12 hours.<br />-- Pneuflex China</span>');
});
});
}
return false;
});
I'm trying to create a form that has a drag and drop image with it. I did a tutorial for the drag and drop and now I'm trying to
put it together with a form.
The problem I'm having is that I'm not able to get the filename, so that I can insert it into the database.
I've tried doing this
if(isset($_POST['add_product']))
{
$filename = $_FILES['files']['name'];
echo print_r($filename);
die();
}
but I get a blank array
Array ( [0] => ) 1
and when I do this
if(isset($_FILES['files']))
{
$filename = $_FILES['files']['name'];
echo print_r($filename);
die();
}
I get the name of my image, but if I do this
if(isset($_FILES['files']))
{
$filename = $_FILES['files']['name'];
}
if(isset($_POST['add_product']))
{
echo print_r($filename);
die();
}
I get a blank array as well
Array ( [0] => ) 1
Here I was hoping that I could grab the $filename and pass it on to the if(isset($_POST['add_product]))
Here is my form
<form action="" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="content">content</label>
<textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea>
</div>
<input type="file" name="files[]" id="standard-upload-files" multiple>
<input type="submit" value="Upload files" id="standard-upload">
<div class="wrapper">
<div class="upload-console">
<h2 class="upload-console-header">
Upload
</h2>
<div class="upload-console-body">
<div class="upload-console-drop" id="drop-zone">
just drag and drop files here
</div>
<div class="bar">
<div class="bar-fill" id="bar-fill">
<div class="bar-fill-text" id="bar-fill-text"></div>
</div>
</div>
<div class="hidden" id="uploads-finished">
<h3>Process files</h3>
<div class="upload-console-upload">
filename.jpg
<span>Success</span>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product">Save</button>
</div>
</form>
Here is the js files that I got from the tutorial that I did.
main.js
(function(){
"use strict";
var dropZone = document.getElementById('drop-zone');
var barFill = document.getElementById('bar-fill');
var barFillText = document.getElementById('bar-fill-text');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files){
// console.log(files);
app.uploader({
files: files,
progressBar: barFill,
progressText: barFillText,
processor: 'index.php',
finished: function(data){
// console.log(data);
var x;
var uploadedElement;
var uploadedAnchor;
var uploadedStatus;
var currFile;
for(x = 0; x < data.length; x = x + 1)
{
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'upload-console-upload';
uploadedAnchor = document.createElement('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded)
{
uploadedAnchor.href = 'uploads/'+currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function(){
console.log('there was an error');
}
});
};
//drop functionality
dropZone.ondrop = function(e){
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function(){
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function(){
this.className = 'upload-console-drop';
return false;
};
}());
upload.js
var app = app || {};
(function(o){
"use strict";
//private methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4)
{
if(this.status === 200)
{
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function')
{
o.options.finished(uploaded);
}
}else{
if(typeof o.options.error === 'function')
{
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(e){
var percent;
if(e.lengthComputable === true)
{
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1)
{
data.append('files[]', source[i]);
}
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined)
{
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined)
{
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(options.files !== undefined)
{
ajax(getFormData(o.options.files));
// getFormData(o.options.files);
}
}
}(app));
I have this in javascript
$('#submit').on('click', function(e) {
$('#message_line').text("");
if(validate_fields_on_submit()) {
e.preventDefault();
return;
}
// e.preventDefault();
var params = $('form').serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
// e.preventDefault();
//return false;
});
function submitHandler(response) {
$('#message_line').text("");
response = $.trim(response);
if(response == "" && response.indexOf("<") <= -1)
$('#registration').submit();
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
return false;
} else {
var name = $('[name="regusername"]').val();
var arr = response.split(',');
arr.pop();
arr.toString();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
return false;
}
$('#busy_wait').css('display','none');
}
HTML CODE
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("db/helper_functions.php");
if(validate_fields()) {
if(!check_duplicate($_POST["regusername"])) {
$count = insert_record($_POST["fname"],$_POST["lname"],$_POST["email"],$_POST["regusername"],$_POST["regpassword"]);
if($count > 0) {
include("includes/confirmation.php");
exit();
}
else {
$error = "Sorry registration failed, please try again.";
}
}
else {
$error = "Username already exists, please try different username.";
}
}
}
$page_title = "Registration";
if(isset($_SESSION["username"]))
include('includes/header_authorized.html');
else
include('includes/header.html');
?>
<div class="container">
<div class="regform">
<form name="registration" id="registration" method="post" action="registration.php">
<p><span class="req">* required field.</span></p>
<ul>
<li><label for="fname">First Name:</label>
<input type="text" class="textboxborder" id="fname" name="fname" size="20" maxlength="25" autofocus="autofocus" value="<?php if(isset($_POST['fname'])) echo $_POST['fname'];?>"/>
<span class="error" id="errfname">*<?php if(isset($errfname)) echo $errfname;?></span>
</li>
<li><label for="lname">Last Name:</label>
<input type="text" class="textboxborder" id="lname" name="lname" size="20" maxlength="25" value="<?php if(isset($_POST['lname'])) echo $_POST['lname'];?>"/>
<span class="error" id ="errlname">*<?php if(isset($errlname)) echo $errlname;?></span>
</li>
<li><label for="email">Email:</label>
<input type="text" class="textboxborder" name="email" id="email" size="40" maxlength="50" placeholder="abc#xyz.com" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/>
<span class="error" id="erremail">*<?php if(isset($erremail)) echo $erremail;?></span>
</li>
<li><label for="regusername">Username:</label>
<input type="text" name="regusername" id="regusername" size="20" maxlength="30" value="<?php if(isset($_POST['regusername'])) echo $_POST['regusername'];?>"/>
<span class="error" id="errregusername">*<?php if(isset($errregusername)) echo $errregusername;?></span>
</li>
<li><label for="regpassword">Password:</label>
<input type="password" name="regpassword" id="regpassword" size="20" maxlength="15" value="<?php if(isset($_POST['regpassword'])) echo $_POST['regpassword'];?>"/>
<span class="error" id="errregpassword">*<?php if(isset($errregpassword)) echo $errregpassword;?></span>
</li>
<li><label for="regconpassword">Confirm Password:</label>
<input type="password" name="regconpassword" id="regconpassword" size="20" maxlength="15"/>
<span class="error" id="errregconpassword">*<?php if(isset($errregconpassword)) echo $errregconpassword;?></span>
</li>
</ul>
<div id="message_line"> <?php if(isset($error)) echo $error;?></div>
<div class="buttons">
<input type="reset" value="Reset" id="reset"/>
<input type="submit" value="Submit" />
</div>
</form>
<img src="images/loading.gif" id="busy_wait" alt="busy wait icon" />
</div>
</div>
</body>
</html>
If in submit handler control goes in else if or else block form submission does not stop,I tried return false; and I tried using e.preventDefault(); at different places before ajax call and after but that stops form submission even after validation success and successful return from check_duplicate.php
Any help would be appreciated.
Assuming you have a submit button with id=submit, I would
rename the button since calling anything submit is poor practice since you need to actually submit the form programatically.
move the handler to the form submit event - I personally NEVER attach a handler to a submit button
I assume you do NOT want to submit if the validation returns false
Like this
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
var params = $(this).serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
});
the post can be written
$.post('check_duplicate.php', params, submitHandler);
UPDATE Here is the complete script - NOTE IMPERATIVE to rename anything name=submit or id=submit to something else
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
$.post('check_duplicate.php', $(this).serialize(), function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
$('#registration').submit(); // actually submit the form
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
Update3:
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
var $thisForm=$(this); // save for later
var params = $thisForm.serialize();
$.post('check_duplicate.php', params, function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
// actually submit the form
$.post($thisForm.prop("action"), params, function(response) {
if (response.indexOf("success") !=-1) {
$('#message_line').text(response);
}
else {
$('#message_line').text("something went wrong");
}
$('#busy_wait').hide();
});
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
To prevent form submission the best method will be to return false on the onclick client event
Eg
$('#submit').click(function(){
return false;
})
I would like to have a html form added in the create_account_success page. Since zen cart has put the customers email address in the db, so I would like to echo the customers email address in this form, so customers no need to key in again. However I have tried several method still cannot echo the customers_email_address, by any chance any people can help?
<div class="centerColumn" id="createAcctSuccess">
<h1 id="createAcctSuccessHeading"><?php echo HEADING_TITLE; ?></h1>
<div id="createAcctSuccessMainContent" class="content"><?php echo TEXT_ACCOUNT_CREATED; ?></div>
<?php
if(REWARD_POINTS_NEW_ACCOUNT_REWARD!=0 && isset($RewardPoints))
if(REWARD_POINTS_NEW_ACCOUNT_REWARD>0 && GetCustomersRewardPoints($_SESSION['customer_id'])==0)
$RewardPoints->AddRewardPoints($_SESSION['customer_id'],REWARD_POINTS_NEW_ACCOUNT_REWARD);
else
if(REWARD_POINTS_NEW_ACCOUNT_REWARD<0 && GetCustomersPendingPoints($_SESSION['customer_id'])==0)
$RewardPoints->AddPendingPoints($_SESSION['customer_id'],abs(REWARD_POINTS_NEW_ACCOUNT_REWARD));
?>
<fieldset>
<legend><?php echo PRIMARY_ADDRESS_TITLE; ?></legend>
<?php
/**
* Used to loop thru and display address book entries
*/
foreach ($addressArray as $addresses) {
?>
<h3 class="addressBookDefaultName"><?php echo zen_output_string_protected($addresses['firstname'] . ' ' . $addresses['lastname']); ?></h3>
<address><?php echo zen_address_format($addresses['format_id'], $addresses['address'], true, ' ', '<br />'); ?></address>
<div class="buttonRow forward"><?php echo '' . zen_image_button(BUTTON_IMAGE_EDIT_SMALL, BUTTON_EDIT_SMALL_ALT) . ' ' . zen_image_button(BUTTON_IMAGE_DELETE, BUTTON_DELETE_ALT) . ''; ?></div>
<br class="clearBoth">
<?php
}
?>
</fieldset>
<div class="buttonRow forward"><?php echo '' . zen_image_button(BUTTON_IMAGE_CONTINUE, BUTTON_CONTINUE_ALT) . ''; ?></div>
</div>
Form
<!-- Begin MailChimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="http://c.us7.list-manage.com/subscribe/post?u=8e1a686f2e7899f845cd4208c&id=79af0d8b9f" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>Subscribe to our mailing list</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="<?php echo $customers_email_address;?>" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="FNAME" class="required" id="mce-FNAME">
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="LNAME" class="required" id="mce-LNAME">
</div>
<div class="mc-field-group">
<label for="mce-MMERGE4">Where did you hear about us? <span class="asterisk">*</span>
</label>
<input type="text" value="" name="MMERGE4" class="required" id="mce-MMERGE4">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_8e1a686f2e7899f845cd4208c_79af0d8b9f" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<script type="text/javascript">
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[4]='MMERGE4';ftypes[4]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://candles.us7.list-manage.com/subscribe/post-json?u=8e1a686f2e7899f845cd4208c&id=79af0d8b9f&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
if (/\[day\]/.test(fields[0].name)){
this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value;
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
}
});
});
$('.phonefield-us','#mc_embed_signup').each(
function(){
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){
this.value = '';
} else {
this.value = 'filled';
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
</script>
<!--End mc_embed_signup-->
Try this:
// Query the database for customers email address by (logged in) customer's ID
$email_results = $db->Execute('SELECT customers_email_address FROM customers WHERE customers_id = ' . $_SESSION['customer_id']);
// The customer's Email Address is now in the PHP variable $email_addr
$email_addr = $email_results->fields['customers_email_address'];
I have an HTML form that posts to a php script that then emails me the forms contents.
I'm also using javascript form validation and some jquery ajax so that the page doesn't reload.
HTML -
<form action="mail.php" class="contactus" onsubmit="return ValidateRequiredFields();" name="contactus" method="POST">
<p class="floatleft" style="width:200px; background-color:#FF0000; line-height:50px; margin:0; padding:0;">Nameeeeee</p> <input class="sizetext" type="text" maxlength="10" name="name">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Email</p> <input class="sizetext" type="text" maxlength="10" name="email">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Telephone</p> <input class="sizetext" type="text" maxlength="10" name="telephone">
<p>Priority</p>
<select name="priority" size="1">
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="High">High</option>
<option value="Emergency">Emergency</option>
</select>
</select>
<p>Message</p><textarea name="message" rows="6" cols="25"></textarea><br />
<br />
<input class="buttonstyle" type="submit" value="Send">
</form>
<div id="formResponse">
</div>
PHP -
<?php $name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemailaddress";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>
Form validation and ajax -
<script type="text/javascript" language="JavaScript">
var FormName = "contactus";
var RequiredFields = "name,email,priority,message";
function ValidateRequiredFields()
{
var FieldList = RequiredFields.split(",")
var BadList = new Array();
for(var i = 0; i < FieldList.length; i++) {
var s = eval('document.' + FormName + '.' + FieldList[i] + '.value');
s = StripSpacesFromEnds(s);
if(s.length < 1) { BadList.push(FieldList[i]); }
}
if(BadList.length < 1) { return true; }
var ess = new String();
if(BadList.length > 1) { ess = 's'; }
var message = new String('\n\nThe following field' + ess + ' are required:\n');
for(var i = 0; i < BadList.length; i++) { message += '\n' + BadList[i]; }
alert(message);
return false;
}
function StripSpacesFromEnds(s)
{
while((s.indexOf(' ',0) == 0) && (s.length> 1)) {
s = s.substring(1,s.length);
}
while((s.lastIndexOf(' ') == (s.length - 1)) && (s.length> 1)) {
s = s.substring(0,(s.length - 1));
}
if((s.indexOf(' ',0) == 0) && (s.length == 1)) { s = ''; }
return s;
}
// -->
</script>
<script type="text/javascript">
$(document).ready(function() {
$(".contactus").submit(function() {
$.post("mail.php", $(".contactus").serialize(),
function(data) {
$("#formResponse").html(data);
}
);
return false;
});
});
</script>
What I'd like to know is how to hide the form after it's submitted.
$(".contactus").on('submit', function() {
$this = $(this);
$.post("mail.php", $(".contactus").serialize(), function(data) {
$("#formResponse").html(data);
$this.hide()
});
return false;
});
Or you could try:
$(document).ready(function() {
$(".contactus").on('submit', function(e) {
e.preventDefault();
$this = $(this);
$.ajax({
type: 'POST',
url: "mail.php",
data: $(".contactus").serialize()
}).done(function() { //done will only hide if the submit is successful, using always instead will alway hide the form
$this.hide();
});
});
});
Try
$('form.contactus').submit(function() {
$(this).hide();
});