Title says it all...I have a contact form that allows four files to be uploaded. If you upload large files, the form actually "forgets" name, phone number, e-mail, etc. At least, I get the error screen telling the user to provide that info, and I don't get the e-mail message.
If I use small files (like, say, a megabyte or less), it works fine, and I get the files, but any more bandwidth and it's like I'm submitting a blank form, even though it goes through the motion of uploading the files (it takes well over a minute before I get the error page).
Here's the source of the form itself, including some PHP:
<?php
ini_set("max_input_time","5");
ini_set("max_execution_time","1");
ini_set("upload_max_filesize","2048M");
ini_set("post_max_size","2048M");
?>
<html>
<head>
<script language="Javascript">
function formValidate() {
// Did the user include a name?
var userName=document.forms["contactRich"]["cName"].value;
if (userName=="" || userName==null) {
alert("Please provide your name.");
return false;
}
// Did the user include a phone number and area code?
var phoneNumber=document.forms["contactRich"]["cNumber"].value;
var areaCode=document.forms["contactRich"]["cAreaCode"].value;
if (phoneNumber=="" || phoneNumber==null || areaCode=="" || areaCode==null) {
alert("Please include your phone number with the area code.");
return false;
}
// Did the user provide a valid e-mail address?
var emailAddress=document.forms["contactRich"]["cEmail"].value;
var atCount=emailAddress.split("#").length-1;
var lastAt=emailAddress.lastIndexOf("#");
var isDot=emailAddress.lastIndexOf(".");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(emailAddress) || emailAddress=="" || emailAddress==null || emailAddress.length<5 || lastAt <0 || isDot<0 || isDot<lastAt || atCount!=1) {
alert("Please provide a valid e-mail address.");
return false;
}
// Did the user select a service?
if (document.forms["contactRich"]["cTopic"].value=="null") {
alert("Please tell us what you need help with.");
return false;
}
document.getElementById("isValid").value="yes";
return true;
}
</script>
<!-- #BeginEditable "doctitle" -->
<title>Contact Rich</title>
<!-- #EndEditable -->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.form { font-family: "Franklin Gothic Medium", "Trebuchet MS"; font-size: 13pt}
-->
</style>
</head>
<body bgcolor="#CCCCCC">
<table width="800" border="0" cellspacing="2" cellpadding="2" align="center" bgcolor="#FFFFFF">
<form name="contactRich" id="contactRich" method="post" action="formHandler2.php" enctype="multipart/form-data" onsubmit="return fabFormValidate()">
<table cellpadding="6">
<tr>
<td colspan="2"><h3>Contact</h3></td>
</tr>
<tr>
<td class="form">Your name:</td>
<td><input type="text" name="cName" size="31"></td>
</tr>
<tr>
<td class="form">Your phone number:<br /><span class="footer">(Include area code)</span></td>
<td>(<input type="text" size="3" maxlength="3" name="cAreaCode"/>) <input type="text" id="cNumber" name="cNumber" size="23"></td>
</tr>
<tr>
<td class="form">Your e-mail address:</td>
<td><input type="text" name="cEmail" size="31"></td>
</tr>
<tr>
<td class="form">What can we help you with?</td>
<td><select name="cTopic">
<option value="null">(Please choose:)</option>
<option value="an estimate">Estimate</option>
<option value="bifold doors">Bifold doors</option>
<option value="broken window ropes">Broken window ropes</option>
<option value="door that won't stay shut">My door won't stay shut!</option>
<option value="noisy doors">My door is noisy!</option>
<option value="sticking doors">My door is sticking!</option>
<option value="drywall repairs">Drywall repairs</option>
<option value="garbage disposals">Garbage disposals</option>
<option value="grab bars">Grab bars</option>
<option value="your various services">(other)</option>
</select></td>
</tr>
<tr>
<td class="form">Any additional details?</td>
<td><textarea name="cAdditional" cols="27" rows="4" wrap="soft"></textarea></td>
</tr>
<tr>
<td class="form">You may include up to<br />four pictures:</td>
<td>
<input type="file" name="file_1" id="file_1" /><br />
<input type="file" name="file_2" id="file_2" /><br />
<input type="file" name="file_3" id="file_3" /><br />
<input type="file" name="file_4" id="file_4" /><br />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
<tr>
<td colspan="2"><hr /></td>
</tr>
</table>
<input type="hidden" id="isValid" name="isValid" value="no" />
</form>
</table>
<p> </p>
</body>
</html>
Here's the PHP that actually processes the data and tries to send it, via PHPMailer:
<?php
ini_set("max_input_time","5");
ini_set("max_execution_time","1");
ini_set("upload_max_filesize","2048M");
ini_set("post_max_size","2048M");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
$error_exists = false;
$masterEmail = "email#goes.here";
require 'PHPMailer-master/PHPMailerAutoload.php';
include "Form.php";
$name = $_POST['cName'];
$areaCode = $_POST['cAreaCode'];
$phone = $_POST['cNumber'];
$email = $_POST['cEmail'];
$from = "from_address#goes.here";
$topic = "(WEB) ".$_POST['cTopic'];
$additional = $_POST['cAdditional'];
$isValid = $_POST['isValid'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r<br /> <br />";
$body = "Name: ".$name."<br /> <br />";
$body = $body."Phone number: (".$areaCode.") ".$phone."<br /> <br />";
$body = $body."E-mail address: ".$email."<br /> <br />";
$body = $body."Needs help with: ".$topic."<br /> <br />";
if (!empty($additional)) {
$body = $body .$additional;
}
$body .= "\n\nIP address: ".$_SERVER['REMOTE_ADDR']."<br /> <br />";
$body .= "Browser: ".$_SERVER['HTTP_USER_AGENT']."<br /> <br />";
$mail = new PHPMailer();
$mail->addAddress($masterEmail);
$mail->setFrom($email, $from);
$mail->Subject = $subject;
$mail->msgHTML($body);
if (isset($_FILES['file_1'])) {
$mail->addAttachment($_FILES['file_1']['tmp_name'],$_FILES['file_1']['name']);
}
if (isset($_FILES['file_2'])) {
$mail->addAttachment($_FILES['file_2']['tmp_name'],$_FILES['file_2']['name']);
}
if (isset($_FILES['file_3'])) {
$mail->addAttachment($_FILES['file_3']['tmp_name'],$_FILES['file_3']['name']);
}
if (isset($_FILES['file_4'])) {
$mail->addAttachment($_FILES['file_4']['tmp_name'],$_FILES['file_4']['name']);
}
if (empty($name)) {
$errors = "Please provide your name.<br />";
$error_exists = true;
}
if (!ctype_digit($areaCode) || strlen($areaCode) != 3 || strlen($phone) < 7) {
$errors .= "Please provide your phone number, including area code.<br />";
$error_exists = true;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "Please enter a valid e-mail address.<br />";
$error_exists = true;
}
if (empty($topic)) {
$errors .= "Please tell us what you need help with.<br/>";
$error_exists = true;
}
?>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<title>Request for Information</title>
</head>
<body bgcolor="#cccccc">
<?php
$f=new fabForm();
$f->setSubject($subject);
$f->setBody($body);
$f->setEmail($email);
$f->setFrom($from);
?>
<p> </p>
<table align="center" bgcolor="#FFFFFF">
<tr>
<td>
<?php
if ($error_exists) {
echo $errors;
echo " <br />";
echo "<a href='contact.php'>Click here to try again.</a>";
} else {
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
</td>
</tr>
</table>
</body>
</html>
Finally, here's the form class I'm using:
<?php
class Form {
private $email;
private $subject;
private $body;
private $from;
private $headers;
// SET methods
public function setEmail($emailAddress) {
$this->email=$emailAddress;
}
public function setSubject($subjectLine) {
$this->subject=$subjectLine;
}
public function setBody($bodyText) {
$this->body=$bodyText;
}
public function setHeaders($sizeHeaders) {
$this->headers=$sizeHeaders;
}
public function setFrom($whoFrom) {
$this->from="From:".$whoFrom."\n".$this->headers;
}
// ACCESSOR METHODS
public function getEmail() {
return $this->email;
}
public function getSubject() {
return $this->subject;
}
public function getBody() {
return $this->body;
}
public function getHeaders() {
return $this->headers;
}
public function getFrom() {
return $this->from;
}
public function sendMail($sendHere) {
if (mail(
$sendHere,
stripslashes($this->getSubject()),
stripslashes($this->getBody()),
$this->getFrom()
)
)
echo("<p>Your request has been sent.</P>");
else
echo("<p>Due to technical difficulties, your request could not be delivered.</p>");
}
}
?>
I can post the PHPMailer source files, but that's practically a whole software package...
But what would cause the form's data to literally be forgotten?? How could I prevent it??? (And limiting file size is not a feasible option.) If it helps, the host is 1and1.com.
when the file is bigger than post_max_size the "POST datas" are erased by PHP
a solution would be to send the file by AJAX before to submit the form. look here to know how to do this :
Upload image with JavaScript from another server via AJAX
Related
The following code worked perfectly before I put them into functions but I cannot figure out how to get this form to work correctly using the functions I created. I know I need to pass variables and create some proper main logic but I really don't know where to go from here. The end product should look something like this form: guestbookonescript
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Guestbook</title>
<meta charset="ISO-8859-1">
</head>
<?php
function check(){
$userErr = $emailErr = $noteErr = "";
$user = $email = $note = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"]))
$userErr = "Please fill out a name.";
else
$user = $_POST["user"];
if (empty($_POST["email"]))
$emailErr = "Please fill out an email.";
else
$email = $_POST["email"];
if (empty($_POST["note"]))
$noteErr = "Please give us your comments.";
else
$note= $_POST["note"];
}
}
function display(){
print<<<TABLE_BLOCK
<h2>Please Sign Our Guestbook</h2>
<form method="post" action="mock.php">
<table>
<tr>
<td>Name:</td><td><input type="text" size="34" name="user" value="" /><span class="error"><br> $userErr</span></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" size="34" name="email" value="" /><span class="error"><br> $emailErr</span></td>
</tr>
<tr>
<td valign="top">Comments: </td><td><textarea rows="5" cols="25" name="note"> </textarea><span class="error"><br> $noteErr</span></td>
</tr>
<tr>
<td></td><td></td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
TABLE_BLOCK;
}
function result(){
print<<<TABLE_BLOCK
<h2>Your Input:</h2>
<table>
<tr>
<td>Name:</td><td>$user</td>
</tr>
<tr>
<td>Email: </td><td>$email</td>
</tr>
<tr>
<td valgin="top">Comments: </td><td>$note</td>
</tr>
</table>
TABLE_BLOCK;
}
if(isset($_REQUEST['submit']))
check();
else
display();
result();
?>
</body>
What Alon is trying to say is that all of your variables are caught in the local scope, to avoid this, you need tell the offending variables that they belong in the global scope. Technically, you don't need to initialize them first, but it's good practice.
Note, you need to ensure that your variables are in the global scope in each function you're using them in.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Guestbook</title>
<meta charset="ISO-8859-1">
</head>
<?php
$userErr = $emailErr = $noteErr = "";
$user = $email = $note = "";
function check(){
global $user, $email, $note;
global $userErr, $emailErr, $noteErr;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"]))
$userErr = "Please fill out a name.";
else
$user = $_POST["user"];
if (empty($_POST["email"]))
$emailErr = "Please fill out an email.";
else
$email = $_POST["email"];
if (empty($_POST["note"]))
$noteErr = "Please give us your comments.";
else
$note = $_POST["note"];
}
}
function display(){
global $userErr, $emailErr, $noteErr;
print<<<TABLE_BLOCK
<h2>Please Sign Our Guestbook</h2>
<form method="post" action="/">
<table>
<tr>
<td>Name:</td><td><input type="text" size="34" name="user" value="" /><span class="error"><br> $userErr</span></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" size="34" name="email" value="" /><span class="error"><br> $emailErr</span></td>
</tr>
<tr>
<td valign="top">Comments: </td><td><textarea rows="5" cols="25" name="note"> </textarea><span class="error"><br> $noteErr</span></td>
</tr>
<tr>
<td></td><td></td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
TABLE_BLOCK;
}
function result(){
global $user, $email, $note;
print<<<TABLE_BLOCK
<h2>Your Input:</h2>
<table>
<tr>
<td>Name:</td><td>$user</td>
</tr>
<tr>
<td>Email: </td><td>$email</td>
</tr>
<tr>
<td valgin="top">Comments: </td><td>$note</td>
</tr>
</table>
TABLE_BLOCK;
}
if(isset($_REQUEST['submit']))
check();
display();
result();
?>
</body>
You need to define variables that was declared outside the function as global. Put this line at start of your function, after function result(){
global $user,$email,$note;
note that variables declared inside the function scope will be deleted after the function execution. you need to declare $user,$email,$note ouside check() (and just declare them as global inside check())
The program I'm working on is supposed to remove dashes, spaces, etc.. from an input box and display the number back to the user.
I am getting an undefined variable and undefined index error in my php code. The errors are on line 35 and 41. I'm guessing the function is out of scope, but I'm not sure.
I made factorial calculator with similar code and it worked fine. I've tried adapting that code to this problem, but I can't get it to work. I don't know why, but I'm having quite a bit of trouble getting an understanding of how php works.
Thanks!
<?php
function getCardNum($cardNum) {
$ccNum = true;
if ($_POST) {
$number = $_POST['cardNum'];
$number = preg_replace('/[\-\" "]/', '', $number);
if (is_numeric($number)) {
$ccNum = true;
}
else {
$ccNum = false;
}
return $number;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Card Validator</title>
<link rel="stylesheet" type="text/css" href="common.css" />
</head>
<body>
<h3>Enter your credit card number!:</h3>
<form method="POST">
<table border="0">
<tr>
<td>Enter numeric character only</td>
<td><input type="text" name="cardNum" id="cardNum" size = "50" /></td>
<td>
<?php
if ($cardNum) {
echo '<p style="color:green;">Number is valid</p>';
echo '<p style="color:green;">' . getCardNum($_POST['cardNum']) . '</p>';
}
else {
echo '<p style="color:red;">Number contains non-numeric characters!</p><br />';
echo '<p style="color:red;">' . getCardNum($_POST['cardNum']) . '</p>';
}
?>
</td>
</tr>
<td><input type="submit" name="cardNum" id="cardNum" value="Submit" /></td>
<td><input type="reset" name="resetButton" id="resetButton" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
if ($_POST) { will always evaluate to true, because $_POST superglobal exists all the time. you will have to do more specific test like if (isset($_POST['cardNum']))
I had to change a few of the conditions, but I think this should work as expected.
The submit input was renamed to submit because it was causing a conflict.
Added if (is_numeric($_POST['cardNum'])) {
and if ((!is_numeric($_POST['cardNum'])) && (isset($_POST['cardNum']))) {
<?php
function getCardNum() {
$ccNum = true;
if(isset($_POST['submit'])) {
$number = $_POST['cardNum'];
$number = preg_replace('/[\-\" "]/', '', $number);
if (is_numeric($number)) {
$ccNum = true;
}
else {
$ccNum = false;
}
return $number;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Card Validator</title>
<link rel="stylesheet" type="text/css" href="common.css" />
</head>
<body>
<h3>Enter your credit card number!:</h3>
<form method="POST" action="">
<table border="0">
<tr>
<td>Enter numeric character only</td>
<td><input type="text" name="cardNum" id="cardNum" size = "50" /></td>
<td>
<?php
if (is_numeric($_POST['cardNum'])) {
echo '<p style="color:green;">Number is valid</p>';
echo '<p style="color:green;">' . getCardNum($_POST['cardNum']) . '</p>';
}
if ((!is_numeric($_POST['cardNum'])) && (isset($_POST['cardNum']))) {
echo '<p style="color:red;">Number contains non-numeric characters!</p><br />';
echo '<p style="color:red;">' . getCardNum($_POST['cardNum']) . '</p>';
}
?>
</td>
</tr>
<td><input type="submit" name="submit" id="cardNum" value="Submit" /></td>
<td><input type="reset" name="resetButton" id="resetButton" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
Use the isset() function before you address keys that you're not sure they exist in an array.
For instance:
if (isset($_POST['cardNum'])) {
echo '<p style="color:green;">Number is valid</p>';
echo '<p style="color:green;">' . getCardNum($_POST['cardNum']) . '</p>';
}
I'm very new to PHP coding.
I've done tons of research to try and help me. As you can imagine I've gotten tons of material for help. The problem is when I'm trying to put it all together.
Specifically here is my problem. I've come across:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "e-Mail is Valid";
} else {
echo "Invalid e-Mail";
}
But I have no idea how to implement it. As it stands now the validator checks the fields before the user has time to imput them..... I'm desperate
I'm sure the solution is really simple, but I've spent hours on this and am really desperate for this problem to be solved already.
Here's a link to the page
Here is the code for the page:
<!DOCTYPE html>
<head>
<meta charset='utf-8'>
<title>AWalsh Photography - Contact Me</title>
<link href="style/main_page.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="email_container">
<h1 class="email_head"> Contact Andrew walsh Photography</h1>
<form id="email_form" name="email_form" method="post">
<table>
<tr>
<td><label for="fname">First Name:</label>
</td>
<td><input type="text" name="fname_input" id="fname_input" /><br>
</td>
</tr>
<tr>
<td><label for="lname">Last Name:</label>
</td>
<td><input type="text" name="lname_input" id="lname_input" /><br>
</td>
</tr>
<tr>
<td><label for="email_input">Your Email:</label>
</td>
<td><input type="text" name="email_input" id="email_input" /><br>
</td>
</tr><tr>
<td><label for="email_conf">Re-enter Email:</label>
</td>
<td><input type="text" name="email_conf" id="email_conf" /><br>
</td>
</tr><tr>
<td>
<label for="message_input">Message </label>
</td><td>
<textarea rows="8" cols="45" id="message_input" name="message_input"></textarea>
</td></tr><tr><td></td>
<td>
<input id="submit"type="submit" value="submit" name="submit"/>
</td></tr>
</table>
</form>
<?php
if($_POST['email_imput'] == $_POST['email_conf']){
//stuff to do on success
echo '<h1>Success!!</h1>';
} else {
//stuff to do on failure
echo '<h1>Sorry, The emails you entered do not match</h1>';
}
$email_imput = $_POST['email_imput'];
if (filter_var($email_imput, FILTER_VALIDATE_EMAIL)) {
echo $email_imput . ' is a valid email address.';
} else {
echo $email_imput . ' is not a valid email address.';
}
$message_imput = $_POST['message_imput'];
$msg = "Email address: $email_imput \n" . "Message: $message_imput";
$to = 'myemail#gmail.com ';
$subject = 'AWP_email';
if (filter_var($email_imput)){
mail($to, $subject, $msg, $email);
}
if (mail($to, $subject, $msg, $email)) {
echo("<p>Message successfully sent! Thanks for submitting your message. We will reply to you as soon as possible</p>");
} else {
echo("<h1>Sorry, There was an error in your imput. Please try again.</h1>");
}
?>
<span class="error"><?=$error;?></span>
<form method="post" action="">
<h1> There was an error with your post</h1>
</form>
</div>
</div>
</body>
</html>
Any input would be amazing. Thank you.
You could add a hidden field into the form and check it's value when it's time to send the email.
if (isset($_POST["some_hidden_field"])) {
// put form validation and sending email here
}
else {
// print the form
}
You should first check whether the page has been submitted or not. You might want to try if ($_SERVER['METHOD'] == 'POST') before making any validations
I am trying to add ReCaptcha into a mail form that I created which is intended for sharing content,
but for some reason the captcha is not being validated when I hit "submit", meaning that even if you enter a wrong text in the captcha, the form will still send the email.
I am using joomla 2.5.8, the recaptcha plugin is enabled (although I don't think it is being intialized since I added the recaptchalib.php myself and I am including the ref to the publickey and privatekey inside the mail form code).
Any help would be very much appreciated!
Thank you!!
here is the code:
<?php require_once('recaptchalib.php'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function validateEmail($email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( $email ) )
{
return false;
}
else
{
return true;
}
}
function validateForm()
{
var form = document.mailForm;
if (form.recipient.value == "" || validateEmail(form.recipient.value)==false)
{
alert("bad email");
return false;
}
if (form.subject.value == "")
{
alert("please enter subject");
return false;
}
if (form.content.value == "")
{
alert("please enter massage");
return false;
}
<?php
$privatekey = "privatekey";
$resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); ?>
if (!$resp->is_valid)
{
alert("try again");
return false;
}
return true;
}
</script>
<?php
if($this->success=='1')
{
echo JText::_('MAIL_SEND_SUCCESSFULLY');
}
elseif($this->success=='0')
{
echo JText::_('MAIL_SEND_FAILED');
}
?>
<div id="SendMail">
<h2>send mail</h2>
<form action="index.php" name="mailForm" method="post" onsubmit="return validateForm()">
<table>
<tr>
<td><label><?php echo JText::_('MAIL_SEND_TO'); ?>:</label></td>
<td><input type="text" name="recipient" size="25" value=""/></td>
</tr>
<tr>
<td><label><?php echo JText::_('MAIL_SUBJECT'); ?>:</label></td>
<td><input type="text" name="subject" size="25" value=""/></td>
</tr>
<tr>
<td><label><?php echo JText::_('MAIL_MESSAGE'); ?>:</label></td>
<td>
<textarea name="content" rows="10" cols="40"></textarea>
<br/><?php echo JText::_('MAIL_DESC'); ?>
</td>
<tr>
<td><?php $publickey = "public key"; ?></td>
<td><?php echo recaptcha_get_html($publickey);?></td>
</tr>
</table>
<p>
<input type="hidden" name="controller" value="mail" />
<input type="hidden" name="task" value="sendMail" />
<div class="button-mail">
<input style="width: 50px;height: 25px;" type="submit" name="submit" value="<?php echo JText::_('SEND'); ?>"/>
<a href="javascript: void window.close()" title="Close Window"><span style="color: #444;
border: #D5D5D5 1px solid; padding: 4px; width: 50px;height: 25px;"><?php echo JText::_('CLOSE'); ?></span></a>
</div>
</p>
</form>
</div>
You have error in the code. Please look this lne
if (!$resp->is_valid)
{
alert("try again");
return false;
}
Where $resp->is_valid is the PHP but executed as JS.
Correct code would be
if (!<php (int)$resp->is_valid;?>)
{
alert("try again");
return false;
}
But it will not work anyway because of 2.
You cannot check recaptcha code in Javascript validation. It should be checked server side. Or if you want to check with javascript it should be checked with AJAX request to server. That is because you code
<?php
$privatekey = "privatekey";
$resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); ?>
is executed on form load before even user eneter captcha.
I have a php form with a jquery validator script that is only validated two out of the four required fields. The two fields that are been validated are the name and the email although if you don't input anything - the error message says 'Alphabetic chars only' rather than 'Please enter your name". The design required that I put the name of each field as a placeholder in the form and I am not sure if this is why it is not working properly. To balance that out - I put the name of each field outside the form and then hid it with a css span class of display none but the script is still not picking it up. Any Suggestions?
<?php
function isRequestSet( $name ) {
if ( isset ( $_REQUEST[$name] ) ) {
return ( $_REQUEST[$name] != "" ) ;
}
return false;
}
$name = "";
if ( isRequestSet('name' ) ) {
$name = $_REQUEST['name'];
}
$number = "";
if ( isRequestSet('number') ) {
$number = $_REQUEST['number'];
}
$email = "";
if ( isRequestSet( 'email' ) ) {
$email = $_REQUEST['email'];
}
$postcode = "";
if ( isRequestSet('postcode' ) ) {
$location = $_REQEUST['postcode'];
}
$how_did_you_hear_about_us = array();
if ( isset( $_REQUEST['how_did_you_hear_about_us'] ) ) {
$how_did_you_hear_about_us = $_REQUEST['how_did_you_hear_about_us'];
}
$message = "";
if ( isRequestSet('message' ) ) {
$location = $_REQEUST['message'];
}
$apartment_price_range = array();
if ( isset( $_REQUEST['apartment_price_range'] ) ) {
$apartment_price_range = $_REQUEST['apartment_price_range'];
}
if ( ($name !="") && ($number != "") && ($email != "") && ($isspam !="yes") ) {
$to = 'name#email.com';
$from = $to;
$headers = 'From: ' . $to . "\n" .
'Reply-To: ' . $to . "\n";
$vars = array( 'name' , 'number' , 'email' , 'postcode' , 'message' ) ;
$message = "-----------\n" ;
foreach ( $vars as $v ) {
$value = $_REQUEST[$v];
$message .= "$v:\t$value\n";
}
$message .= "-----------\n" ;
$message .= "\nHow did you hear about us?:\n" ;
foreach ( $how_did_you_hear_about_us as $how_did_you_hear_about_us ) {
$message .= "$how_did_you_hear_about_us\n" ;
}
$message .= "-----------\n" ;
$message .= "\nApartment price range:\n" ;
foreach ( $apartment_price_range as $apartment_price_range ) {
$message .= "$apartment_price_range\n" ;
}
$subject = "From: $name <$email>";
mail( $to , $subject , $message , $headers, "-f $from" );
$confirm = true;
} else {
$confirm = false;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="css/graphite.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/graphitephone.css" rel="stylesheet" media="handheld, only screen and (max-device-width: 480px)" />
<script src="js/gen_validatorv4.js" type="text/javascript"></script>
<style>
span {display: none;}</style>
</head>
<body onload="javascript:preload">
<div id="container">
<div id="header"><img src="images/HomeBanner.jpg" width="900" height="162" border="0" />
<div id="ruler"></div><!--end header-->
<div id="nav">
<ul>
<li class="list1"><span class="none">STORY</span></li>
<li class="list2"><span class="none">APARTMENTS</span>
<ul>
<li class="list7"><span class="none">GALLERY</span></li>
<li class="list8"><span class="none">FLOORPLANS</span></li>
</ul>
</li>
<li class="list3"><span class="none">MEET THE LOCALS</span></li>
<li class="list4"><span class="none">MEET THE CREATORS</span></li>
<li class="list5"><span class="none">LOCATION</span></li>
<li class="current6"><span class="none">CONTACT</span></li>
</ul>
</div><!--end nav-->
<div id="main">
<div id="contactform">
<table width="250px" border="0" cellspacing="0px" cellpadding="0px">
<form name="myform" method="post" action="" />
<input type='hidden' name='submitted' value='yes' />
<tr>
<td colspan="2"><?php
if ($confirm ) {
echo "<p>Thank you for enquiry</p>
<p>We will contact you shortly to advise on apartment availability and pricing.<p>";
} else {
if (isRequestSet( 'submitted' ) && $_REQUEST['submitted'] == "yes" ) {
echo "Request not sent, please complete all required fields marked '*'.";
}
}
?></td>
</tr>
<tr>
<td colspan="2" valign="middle"><p><span>name</span><input type="text" name="name" placeholder="Name*" id="contact_name" /></p></td>
</tr>
<tr>
<td colspan="2" valign="middle">
<table width="250px" border="0" cellspacing="0px" cellpadding="0px">
<tr>
<td bgcolor="#FFF" valign="baseline" height="10px"><p><img src="images/spacer.gif" width="1" height="5" /><span>number</span><input type="text" name="number" placeholder="Contact Number*" id="contact_number" /></p></td>
<td width="8px" height="10px"><img src="images/spacer.gif" width="8" height="5" /></td>
<td bgcolor="#FFF" valign="baseline" height="10px"><p><img src="images/spacer.gif" width="1" height="5" /><span>postcode</span><input type="text" name="postcode" placeholder="Postcode*" id="contact_postcode" /></p></td>
</tr>
<tr><td><img src="images/spacer.gif" width="1" height="6" /></td></tr>
</table></td></tr>
<tr>
<td colspan="2" valign="middle"><p><span>email</span><input type="text" name="email" placeholder="Email*" id="contact_email" /></p></td>
</tr>
<tr>
<td colspan="2"><p><select name="how_did_you_hear_about_us[]" id="" class='select-box'>
<option label="How did you hear about us?" value="0">How did you hear about us?</option>
<option label="realestate.com.au" value="realestate.com.au">realestate.com.au</option>
<option label="domain.com.au" value="domain.com.au">domain.com.au</option>
<option label="the age" value="the age">the age</option>
<option label="the herald sun" value="the herald sun">the herald sun</option>
<option label="billboard" value="billboard">billboard</option>
<option label="bpmcorp.com.au" value="bpmcorp.com.au">bpmcorp.com.au</option>
<option label="google" value="google">google</option>
<option label="site signage" value="site signage">site signage</option>
<option label="other" value="other">other - please state in box below</option>
</select></p></td>
</tr>
<tr>
<td colspan="2"><p>
<textarea name="message" cols="33" style="background:#fff; border:0px;" placeholder="What would you like to know?"></textarea>
</p></td>
</tr>
<tr>
<td><p>Price?</p></td><td rowspan="4" valign="top" align="right"><input type="image" class="rollover" id="contact_submit" src="images/buttons/BTN_Submit.png" alt="Submit" width="72px" height="68px" border="0" hover="images/BTN_Submit_over.png" name="Submit" value="Login"></td>
</tr>
<tr>
<td valign="middle"><p><input name="apartment_price_range[]" type="checkbox" value="350k-400k" style="background:#F9DC31; color: #000000;" /> 350k-400k</p></td></tr>
<tr>
<td><p><input name="apartment_price_range[]" type="checkbox" value="450k-550k" background="#F9DC31" /> 450k-550k</p></td></tr>
<tr><td><p><input name="apartment_price_range[]" type="checkbox" value="550k+" background="#F9DC31" /> 550k+</p></td></tr>
</form>
<tr><td colspan="2"><p class="italics" style="font-size:10px;">* denotes a required field</p> </td>
</tr>
<tr>
<td colspan="2"></td></tr>
</table>
</div><!--end contact form-->
</div><!--end left-->
</div><!--end main-->
</div><!--end container-->
<script language="JavaScript" type="text/javascript"
xml:space="preserve">//<![CDATA[
//You should create the validator only after the definition of the HTML form
var frmvalidator = new Validator("myform");
frmvalidator.addValidation("name","req","Please enter your name");
frmvalidator.addValidation("name","alpha_s","Alphabetic chars only");
frmvalidator.addValidation("number","maxlen=50");
frmvalidator.addValidation("number","req");
frmvalidator.addValidation("number","numeric_s", "Numbers only");
frmvalidator.addValidation("postcode","maxlen=50");
frmvalidator.addValidation("postcode","req");
frmvalidator.addValidation("postcode","numeric_s", "Numbers only");
frmvalidator.addValidation("email","maxlen=50");
frmvalidator.addValidation("email","req");
frmvalidator.addValidation("email","email");
//]]></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
</script>
<script src="js/load.js" type="text/javascript"></script>
</body>
</html>
"Name" gets validates as "has content" as the javascript records a value of "Name*" from the placeholder text. (Follow through in line 1088 of gen_validatorv4.js - objValue has a value of the placeholder text).
Also, as the placeholder text has an asterisk, this is not an alpha numeric - so it fails that clause - hence you see the message you see.
So, you're right, the placeholders, when pumped into the INPUT as "values" must then be removed when you validate. You could probably do this with "form_submit_handler()" by saying "if the value is the same as the placeholder, remove hte value before processing... and restore afterwards"
Another option is that I'd suggest looking at the jQuery validator at http://bassistance.de/jquery-plugins/jquery-plugin-validation/ - it's better documented as you're already running jQuery. You'll have the same problem, though, but there are pre-validation and post-validation hooks you can use to adjust the values. Just switch based on if ($('#contact_name').val() == '[placeholderText]') { $('#contact_name').val(''); }
A bit fiddly, but if you MUST have field names inside inputs, then that's a solution. (There are also other solutions involving background graphics or semi-transparent input fields. None are perfect.)