How to set my own upload size of attachment? - php

I want to set on this PHP code my own size limit of attachment.
I've tried lot of codes but anything isn't working.
Can u help me with it? What working code should I use there?
I want to set maximum size to 2MB, and there should be message ,,Sorry, this attachment is too big (or sth else - it's for check that it's working)".
And how to definite types to attach? For example I want only PNG and JPG to upload. How to do that on my code? And there should be message too, for example - ,,Sorry, you can only attach PNG and JPG files."
NOTE! EVERYTHING IS WORKING RIGHT. I ONLY WANT TO CHANGE UPLOAD SIZE AND MAKE PNG AND JPG FILES :) THANKS!
Here is my PHP code:
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
if(!empty($_POST["send"])) {
require_once ('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->Port = 587;
$mail->Username = "wlasciciel#rubinmc.pl";
$mail->Password = "XXXXXXXXX";
$mail->Mailer = "smtp";
if (isset($_POST["userEmail"])) {
$userEmail = $_POST["userEmail"];
}
if (isset($_POST["userName"])) {
$userName = $_POST["userName"];
}
if (isset($_POST["subject"])) {
$subject = $_POST["subject"];
}
if (isset($_POST["userMessage"])) {
$message = $_POST["userMessage"];
}
if (isset($_POST["NickCheatera"])) {
$NickCheatera = $_POST["NickCheatera"];
}
$mail->SetFrom('wlasciciel#rubinmc.pl', $userName);
$mail->AddReplyTo($userEmail, $userName);
$mail->AddAddress("wlasciciel#rubinmc.pl"); // set recipient email address
$mail->Subject = 'Zgloszenie';
$mail->Body = join('', array(
'Wiadomosc od: ',
$_POST['userName'],
'<br/>',
'E-mail: ',
$_POST['userEmail'],
'<br/>',
'Nick cheatera: ',
$_POST['NickCheatera'],
'<br/>',
'Powod: ',
$_POST['subject'],
'<br/>',
'Dodatkowe informacje: ',
'<br/>',
$_POST['userMessage'],
'<br/>'
));
$mail->WordWrap = 80;
$mail->IsHTML(true);
$mail->SMTPSecure = 'tls';
$mail->Host = 'serwer2092488.home.pl';
if (! empty($_FILES['attachment'])) {
$count = count($_FILES['attachment']['name']);
if ($count > 0) {
// Attaching multiple files with the email
for ($i = 0; $i < $count; $i ++) {
if (! empty($_FILES["attachment"]["name"])) {
$tempFileName = $_FILES["attachment"]["tmp_name"][$i];
$fileName = $_FILES["attachment"]["name"][$i];
$mail->AddAttachment($tempFileName, $fileName);
}
}
}
}
if (! $mail->Send()) {
$message = "Wystąpił problem podczas wysyłania e-maila. Spróbuj ponownie.";
$type = "error";
} else {
$message = "Dziękujemy za zgłoszenie! Odpowiemy do 24 godzin.";
$type = "success";
}
}
HTML code:
<?php
require_once "mail-sending-script.php";
iconv_set_encoding("internal_encoding", "UTF-8");
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="style.css" rel="stylesheet" type="text/css" />
<title>RubinMC - zgłoś cheatera</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function validate() {
var valid = true;
$(".info").html("");
var userName = document.forms["mailForm"]["userName"].value;
var userEmail = document.forms["mailForm"]["userEmail"].value;
var NickCheatera = document.forms["mailForm"]["NickCheatera"].value;
var subject = document.forms["mailForm"]["subject"].value;
var userMessage = document.forms["mailForm"]["userMessage"].value;
if (userName == "") {
$("#userName-info").html("(To pole jest wymagane.)");
$("#userName").css('background-color', '#FFFFDF');
valid = false;
}
if (userEmail == "") {
$("#userEmail-info").html("(To pole jest wymagane.)");
$("#userEmail").css('background-color', '#FFFFDF');
valid = false;
}
if (!userEmail.match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
$("#userEmail-info").html("(Zły format e-maila.)");
$("#userEmail").css('background-color', '#FFFFDF');
valid = false;
}
if (NickCheatera == "") {
$("#NickCheatera-info").html("(To pole jest wymagane.)");
$("#NickCheatera").css('background-color', '#FFFFDF');
valid = false;
}
if (subject == "") {
$("#subject-info").html("(To pole jest wymagane.)");
$("#subject").css('background-color', '#FFFFDF');
valid = false;
}
if (userMessage == "") {
$("#userMessage-info").html("(To pole jest wymagane.)");
$("#userMessage").css('background-color', '#FFFFDF');
valid = false;
}
return valid;
}
</script>
</head>
<body>
<h1 style="text-align: center">Zgłoś cheatera</h1>
<div class="attachment-form-container">
<form name="mailForm" id="mailForm" method="post" action=""
enctype="multipart/form-data" onsubmit="return validate()">
<div class="input-row">
<label style="padding-top: 20px;">Nick</label> <span
id="userName-info" class="info"></span><br /> <input
type="text" class="input-field" placeholder="Wpisz swój nick..." name="userName"
id="userName" />
</div>
<div class="input-row">
<label>E-mail</label> <span id="userEmail-info"
class="info"></span><br /> <input type="text"
class="input-field" name="userEmail" placeholder="Wpisz adres e-mail..."
id="userEmail" />
</div>
<div class="input-row">
<label>Nick cheatera</label> <span id="NickCheatera-info"
class="info"></span><br /> <input type="text"
class="input-field" name="NickCheatera" placeholder="Wpisz nick cheatera..."
id="NickCheatera" />
</div>
<div class="input-row">
<label for="subject">Powód</label>
<select id="subject" name="subject" class="input-field">
<option disabled selected>Wybierz powód</option>
<option id="Spam">Spam</option>
<option id="X-Ray">X-Ray</option>
<option value="Sales3">Sales2</option>
</select>
</div>
<div class="input-row">
<label>Dodatkowe informacje</label> <span id="userMessage-info"
class="info"></span><br />
<textarea name="userMessage" id="userMessage"
class="input-field" id="userMessage" placeholder="Wpisz dodatkowe informacje..."
cols="60"
rows="6"></textarea><br />
<label>Dodaj załącznik</label>
</div>
<div class="attachment-row">
<input type="file" class="input-field"
name="attachment[]">
</div>
<div>
<input type="submit" name="send" style="position: relative; left: 210px" class="btn-
submit"
value="Wyślij" />
<div id="statusMessage">
<?php
if (! empty($message)) {
?>
<p class='<?php echo $type; ?>Message'><?php echo $message; ?></p>
<?php
}
?>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function() {
var inputPreview = $(".input-preview"),
input = $(".input");
TweenMax.set(input, {
scale: 1.2,
alpha: 0
});
inputPreview.on("click", function(){
var that = $(this);
that.toggleClass("active");
if(that.hasClass("active")){
TweenMax.staggerTo(input, 1.25, {
scale: 1,
alpha: 1,
ease: Elastic.easeOut
}, .1);
}
else {
TweenMax.staggerTo(input, 1, {
scale: 1.2,
alpha: 0,
ease: Elastic.easeOut
}, .1);
}
});
input.on("click", function() {
var tlInput = new TimelineMax({
onComplete: done
});
var that = $(this),
siblings = that.siblings(".input"),
data = that.data("val"),
top = that.css("top");
siblings.removeClass("active");
tlInput.to(siblings, .25, {
alpha: 0
})
.to(that, .25, {
scale: 1.2
})
.to(that, .25, {
top: 0,
})
.set(inputPreview, {
display: "none"
})
.to(that, .25, {
scale: 1,
})
.to(that, .5, {
backgroundColor: "#1D77EF"
})
.set(inputPreview, {
text: data,
display: "block"
})
.to(that, .25, {
alpha: 0
})
function done() {
inputPreview.removeClass("active");
that.css("top", top).addClass("active");
TweenMax.set(input, {
scale: 1.2,
alpha: 0,
backgroundColor: "#fff"
});
}
});
// copy
balapaCop("Select Input Interaction", "rgba(255,255,255,.5)");
});
</script>
</body>
</html>

Try by changing upload_max_filesize in php.ini.

Related

How to validate captcha field code?

I am trying to validate a captcha code field so if the code they enter is correct it will take them to a thank you page with the download link, but if the security code they entered is incorrect then they will see a sorry message and to return back to previous page.
The issue I am facing is when I enter the captcha into this field and click submit the data is always no.
My form is a as follows:
<form action="" name="downloadform" id="downloadform" class="downloadform" method="post">
<div class="field">
<input name="name" type="text" id="name" class="input name" placeholder="Name..." />
</div>
<div class="field">
<input name="company" type="text" id="company" class="input company" placeholder="Company..." />
</div>
<div class="field">
<input name="tel" type="text" id="tel" class="input tel" placeholder="Telephone..." />
</div>
<div class="field">
<input name="email" type="text" id="email" class="input email" placeholder="Email Address..." />
</div>
<div class="field">
<img src="/CaptchaSecurityImages.php" alt="Captcha" class="captcha" />
<input type="text" name="sec_code" id="sec_code" class="input sec_code" placeholder="Please enter the characters above" />
</div>
<div class="field">
<div class="medium secondary btn"><input type="submit" name="Submit2" value="Send Request" class="btn" id="downloadbtn" /></div>
<input type="hidden" name="product" id="product" class="product" value="<?php echo $page[3]; ?>" />
</div>
</form>
My ajax form file looks like this:
$(function() {
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#downloadbtn").click(function() {
var name = $("#name").val();
var company = $("#company").val();
var tel = $("#tel").val();
var email = $("#email").val();
var product = $("#product").val();
var sec_code = $("#sec_code").val();
if (name == "") {
$("#name").focus();
$("#name").val("");
$("#name").css({background:"#b72a18", color:"#fff"});
return false;
}
if (company == "") {
$("#company ").focus();
$("#company ").val("");
$("#company ").css({background:"#b72a18", color:"#fff"});
return false;
}
if (tel == "") {
$("#tel").focus();
$("#tel").val("");
$("#tel").css({background:"#b72a18", color:"#fff"});
return false;
}
if (!filter.test(email)) {
$("#email").focus();
$("#email").val("");
$("#email").css({background:"#b72a18", color:"#fff"});
return false;
}
if (product == "") {
$("#product").focus();
$("#product").val("");
$("#product").css({background:"#b72a18", color:"#fff"});
return false;
}
if (sec_code == "") {
$("#sec_code").focus();
$("#sec_code").val("");
$("#sec_code").css({background:"#b72a18", color:"#fff"});
return false;
}
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>');
var dataString = '&name=' + name + '&tel=' + tel + '&company=' + company + '&email=' + email + '&product=' + product + '&sec_code=' + sec_code + '&type=download';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/process_download.php",
data: dataString,
datatype: 'json',
success: function(data) {
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>')
.hide()
.fadeIn(1500, function() {});
setTimeout(function ()
{
$(window.location).attr('href', '/process.php?download=' + data.product + '&sec_code=' + data.sec_code);
}, 2000);
}
});
return false;
});
});
Then I have my process download file:
<?php
session_start();
header("Content-type: application/json");
ob_start();
include('inc/connection.php');
$product = $_POST['product'];
$sec_code = $_SESSION['security_code'] == $_POST['sec_code'] ? 'yes' : 'no';
ob_end_clean();
$data = array('product'=>$product,'sec_code'=>$sec_code);
print json_encode($data);
die();
?>
Then the final process:
<?php
session_start();
include('inc/connection.php');
$sec_code = $_GET['sec_code'];
$proddownlink = $_GET['download'];
$proddownl = str_replace("_", " ", $_GET['download']);
$proddownl = ucwords($proddownl);
if ($sec_code == 'no') {
$message = '<p>Security code is wrong. Please click here to return back.</p>';
} else {
$message = '<p>Thank you for downloading ' . $proddownl . ' Data Sheet.</p>
<p>Please click here to download ' . $proddownl . ' PDF.</p>';
include_once('inc/connection.php');
include_once('inc/class.phpmailer.php');
$name = $_POST['name'];
$company = $_POST['company'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$product = $_POST['product'];
$sec_code = $_POST['sec_code'];
$type = $_POST['type'];
$bodytext = "<ul>
<li><strong>Name:</strong> $name</li>
<li><strong>Company:</strong> $company</li>
<li><strong>Telephone Number:</strong> $tel</li>
<li><strong>Email Address:</strong> $email</li>
<li><strong>Area of Interest:</strong> $product</li>
</ul>";
$subject = "New Enquiry";
$query = "insert into user_email set name = '$name', email = '$email', tel = '$tel', type = '$type', message = '$bodytext'";
$result = $conn->query($query);
if(!$result) die($conn->error);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $bodytext;
$mail->From = "sales#fidelitysystems.co.uk";
$mail->FromName = $name;
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
#$mail->AddAddress("sales#fidelitysystems.co.uk");
$mail->AddAddress("craig#arrivaldesign.co.uk");
$mail->IsSMTP();
$mail->SMTPAuth = "true";
$mail->Username = "postmaster#arrivalbusiness.co.uk";
$mail->Password = "edward";
$mail->Host = "mail.arrivalbusiness.co.uk";
$mail->Port = 587;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>

PHPMailer() ajax request

In my quest to validate a form with PHP and $.ajax() and send a mail to my own mail adress having as sender my own gmail adress, as subject the user name and email from the form. Bassically I want the site to notify me that an user left me a message along with his name and adress si I can answer to him. When I try to send I receive an error.
I took the script from PHPMailer example but I cannot figure out where the mail body should be. I have the php file:
<?php
error_reporting(E_ALL);
ini_set('display_errors',true);
// require_once 'class.phpmailer.php';
require 'PHPMailerAutoload.php';
sleep(1);
$mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\ [[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';
$return = array();
$mesaj = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {
$mesaj = "Please enter your name!";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) {
$mesaj = "Please enter your e-mail!";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} elseif (empty($_POST['inputMess'])) {
$mesaj = "Please tell us something";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} else {
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "tavitudor124#gmail.com";
$mail->Password = "**********";
$mail->SetFrom('tavitudor124#gmail.com' , 'First Last');
$mail->Subject = $_POST['inputName'].'/'.$_POST['inputEmail'].'wrote';
//$mail->MsgHTML($body);
$address = 'tavi_tudor#yahoo.com';
$mail->AddAddress($address, "John Doe");
$mail->Body = $_POST['inputMess'];
if (!$mail->Send()) {
$mesaj = 'The message cannot be delivered, please try again later!';
$return['msg'] = 'The message cannot be delivered, please try again later!';
echo json_encode($return);
exit();
} else {
$mesaj = 'Thank you for getting in touch. We will contact you!';
// $return["error"] = false;
$return["msg"] = 'Thank you for getting in touch. We will contact you! '.$mail- >ErrorInfo;
echo json_encode($return);
exit();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NRDC Environmental N.G.O.</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/marin.js"></script>
</head>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<h3 class="masthead-brand">NRDC<br />Save our Planet O.N.G.</h3>
<ul class="nav masthead-nav">
<li>Home</li>
<li>Gallery</li>
<li class="active">Contact</li>
<li>Join Us</li>
</ul>
</div>
</div>
<div class="inner cover">
<div class="row">
<div class="col-xs-12" style="text-align:center;font-size:22px;">
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="inputName">Your name</label>
<input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name">
</div>
<div class="form-group">
<label for="inputEmail">Your e-mail</label>
<input type="text" name="inputEmail" class="form-control" id="inputEmail" placeholder="E-mail">
</div>
<div class="form-group">
<label for="inputMess">Your message for us</label>
<textarea name="inputMess" class="form-control" id="inputMess"> </textarea>
</div>
<button type="submit" name="send" class="btn btn-default">Send</button>
</form>
<div id='mess'> </div>
</div>
</div>
</div>
<div class="mastfoot">
<div class="inner">
<p id="footer">©All rights reserved to NRDC, by TaoAppz</p>
</div>
</div>
</div>
</div>
</div>
JS
$(document).ready(function() {
var email_reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
$('form').submit(function(event) {
event.preventDefault();
if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) {
alert('Please enter your name');
} else if (!email_reg.test($('#inputEmail').val())) {
alert('Please enter a valid e-mail adress');
} else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) {
alert('Please tell us something');
} else {
var formData = $('form').serialize();
submitForm(formData);
}
})
function submitForm(formData) {
$.ajax({
type: 'POST',
url: $('form').action,
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
beforeSend: function() {
$('#mess').text('Processing...');
},
success: function(data) {
$('#mess').text(data.msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#mess').text('Error! ' + textStatus + ' ' + errorThrown + ' ' + 'Please try again later!');
},
complete: function(XMLHttpRequest, status) {
//$('form')[0].reset();
}
})
}
})
It was a mistake on my include in php and the '$mail->Debugoutput = 'html' created html output that was pasrsed as JSON.
So I took out the debugg mode from PHPMailer and now I have a nice working contact form using ajax and PHPMailer. Thanks for your help

Zen Cart Echo Customers email address in my html form

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'];

Hide html form after submission?

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();
});

PHP questionnaire strategy

I am designing a questionnaire, the code I've written is a combination of JS and PHP. I have the questions in one page but I want to ask each question on a separate page and the consecutive questions should be asked according to the answer the user select. what is the best strategy to do that? do I need to include SQL as well?
and at the end the answers will be written in a text file
the code I have is:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['name']))
{
$errorMessage .= "<li>You forgot to enter your name!</li>";
}
$varName = $_POST['name'];
$varLand1 = $_POST['landscape1']; $varLand2 = $_POST['landscape2'];
$varCom = $_POST['comment'];
$varAppx = $_POST['appx'];
$clim = $_POST['landscape'];
$varMech = $_POST['mechanism'];
$varMechoth = $_POST['mech'];
if(empty($errorMessage))
{
$fs = fopen("$varName.txt" ,"a+");
fwrite($fs,$varName . "\n" . $varLand1 . ' ' .$varLand2 . "\n" . $clim . "\n" . $varAppx . "\n" . $varCom . "\n" . $varMech .$varMechoth);
fclose($fs);
header("Location: t-y.html");
exit;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script scr="jss.js" type="text/javascript"></script>
<title>Questionnaire</title>
</head>
<body>
<FONT FACE="Times New RomanPS">
<H1>Questionnaire</H1>
<P>Please fill out this questionnaire:
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="index.php" method="post">
<p>
Name<br>
<input type="text" name="name" maxlength="50" value="<?=$varName;?>" />
</p>
<ul>
<p> 1 - Q1?
<p><input type="checkbox" name="landscape1" value="urban"> Urban<br>
<p><input type="checkbox" name="landscape2" value="non-urban"> non-Urban<br>
<p> 2 - Q2?<br>
<input type="radio" name="landscape" value="Dry"> Dry<br>
<input type="radio" name="landscape" value="Tropical"> Tropical<br>
<input type="radio" name="landscape" value="Moderate"> Moderate<br>
<input type="radio" name="landscape" value="Continental"> Continental<br>
<input type="radio" name="landscape" value="Polar"> Polar<br>
<p> 3 - Q3? <br>
<input type="radio" id="mecha" name="mechanism" value="sub" onclick="hideTextBox1()"/> Subsidence<br>
<input type="radio" id="mecha" name="mechanism" value="earth" onclick="hideTextBox1()"/> Earthquake<br>
<input type="radio" id="mecha" name="mechanism" value="volc" onclick="hideTextBox1()"/> Volcanic<br>
<input type="radio" id="mecha" name="mechanism" value="<?=$varMech;?>" onclick="displayTextBox1()"/> other<br>
<div id="otherTextBox1" style="display:none;visibility:hidden;">
<input type="text" name="mech" maxlength="20" value="<?=$varMech;?>">
</div>
<p> 4 - Q3?<br>
<input name="choice" id="choice4" type="radio" value="four" onclick="hideTextBox()"/><label for="choice4"> No </label><br>
<input name="choice" id="choice5" type="radio" value="other" onclick="displayTextBox()"/><label for="choice5"> Yes </label>
<br/>
<div id="otherTextBox" style="display:none;visibility:hidden;">
[mm/yr]<br><input type="text" name="appx" maxlength="3" value="<?=$varAppx;?>">
</div>
<br/>
<p> 5 - Q4
<p> 6 - Q5
<p> 7 - Q6
<p>
Comments:<br>
<textarea type="text" name="comment" cols=48 rows=4 maxlength="1000" value=" <?=$varComment;?>"></textarea>
</p>
<p><input type="reset"> <input type="submit" name="formSubmit" value="Submit" />
</ul>
<script>
function displayTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'block';
otherTextBox.style.visibility = 'visible';
}
function hideTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'none';
otherTextBox.style.visibility = 'hidden';
}
function validate()
{
var arrElements = document.getElementsByName('choice');
var objElement;
var boolContinue = false;
var objOtherText;
for(var i=0, _length=arrElements.length; i<_length; i++)
{
objElement = arrElements[i];
if(objElement.checked)
{
if(objElement.id == 'choice5')
{
objOtherText = document.getElementById('othertext');
if(strTrim(objOtherText.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else
{
alert('Ask user to complete the data.')
}
}
function displayTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'block';
otherTextBox1.style.visibility = 'visible';
}
function hideTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'none';
otherTextBox1.style.visibility = 'hidden';
}
function validate1()
{
var arrElements1 = document.getElementsByName('mechanism');
var objElement1;
var boolContinue = false;
var objotherText1;
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else<?=$varMech;?>
{
alert('Ask user to complete the data.')
}
}
/**
* Removes all white space characters from the string.
*
* #param: {String} String to trim.
*
* #return {String} Trimed string.
*/
function strTrim(strTrim)
{
return strTrim.replace(/^\s+|\s+$/g, '');
}
</script>
</form>
</FONT>
</body>
</html>
I don't think you would NEED to use SQL to do this. You should be able to use the $_SESSION to store the answers to previous questions and adjust the questions on the following pages accordingly.

Categories