I have a simple Contact Form
it works very freat but I want the result on the same page in a small box
just under the form
where the fail messages are coming and success too
<form method="post" action="contact.php" name="contactform" id="contactform">
<div class="one_half">
<input name="name" type="text" id="name" size="30" onfocus="if(this.value == 'Name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Name'; }" value="Name">
<input name="alter" type="text" id="alter" size="3" onfocus="if(this.value == 'Alter') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Alter'; }" value="Alter">
<input name="email" type="text" id="email" size="30" onfocus="if(this.value == 'E-Mail') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'E-Mail'; }" value="E-Mail">
<input name="phone" type="text" id="phone" size="30" onfocus="if(this.value == 'Handynummer') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Handynummer'; }" value="Handynummer">
<input name="facebook" type="text" id="facebook" size="200" onfocus="if(this.value == 'Facebook') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Facebook'; }" value="Facebook">
<input name="instagram" type="text" id="instagram" size="200" onfocus="if(this.value == 'Instagram') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Instagram'; }" value="Instagram">
</div>
<div class="one_half last">
<textarea name="comments" cols="40" rows="3" id="comments" onfocus="if(this.value == 'Nachricht') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Nachricht'; }">Nachricht</textarea>
</div>
<input type="submit" class="send_message" id="submit" value="Senden"/>
</form>
and here the PHP file
<?php
if (!$_POST) exit;
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
$alter = $_POST['alter'];
$facebook = $_POST['facebook'];
$instagram = $_POST['instagram'];
if (get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "xxx#xxx.de";
$e_subject = 'Contact from ' . $name;
$e_body = "von: $name" . PHP_EOL . PHP_EOL;
$e_reply = "Alter: $alter\r\nE-mail: $email\r\nHandynummer: $phone";
$e_content = "Nachricht:\r\n$comments" . PHP_EOL . PHP_EOL;
$e_links = "Facebook:\r\n$facebook\r\nInstagram:\r\n$instagram" . PHP_EOL . PHP_EOL;
$msg = wordwrap($e_body . $e_links . $e_content . $e_reply, 70);
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if (mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h1>Bewerbung erfolgreich</h1>";
echo "<p>Danke <strong>$name</strong>, deine Bewerbung wurde erfolgreich an uns gesendet</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'FEHLER!';
}
It works PERFECT
but it's always getting on a new site, no matter if error or success.
I want to add a small block under the form where all results are displayed
I hope u can help me.
I don't want ajax or something else. I just want it added like it is.
A solution for your problem might be to have in the same PHP file the logic with the form rendering. Doing this, the form action will be the same PHP file, so it will load the PHP code before rendering the form view. By that, you'll be able to render bellow the form whatever you want to according with the output from the sending email.
For example, take a closer look at the $mailResult variable:
<?php
$name = $_POST['name'] ?? null;
$email = $_POST['email'] ?? null;
$phone = $_POST['phone'] ?? null;
$comments = $_POST['comments'] ?? null;
$alter = $_POST['alter'] ?? null;
$facebook = $_POST['facebook'] ?? null;
$instagram = $_POST['instagram'] ?? null;
if (get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "xxx#xxx.de";
$e_subject = 'Contact from ' . $name;
$e_body = "von: $name" . PHP_EOL . PHP_EOL;
$e_reply = "Alter: $alter\r\nE-mail: $email\r\nHandynummer: $phone";
$e_content = "Nachricht:\r\n$comments" . PHP_EOL . PHP_EOL;
$e_links = "Facebook:\r\n$facebook\r\nInstagram:\r\n$instagram" . PHP_EOL . PHP_EOL;
$msg = wordwrap($e_body . $e_links . $e_content . $e_reply, 70);
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
$mailResult = '';
if (isset($name, $email)) {
if (mail($address, $e_subject, $msg, $headers)) {
$mailResult = "<fieldset>";
$mailResult .= "<div id='success_page'>";
$mailResult .= "<h1>Bewerbung erfolgreich</h1>";
$mailResult .= "<p>Danke <strong>$name</strong>, deine Bewerbung wurde erfolgreich an uns gesendet</p>";
$mailResult .= "</div>";
$mailResult .= "</fieldset>";
} else {
$mailResult .= 'FEHLER!';
}
}
?>
<html lang="en">
<head>
<title>Title page!</title>
</head>
<body>
<form method="post" name="contactform" id="contactform">
<div class="one_half">
<input name="name" type="text" id="name" size="30"
onfocus="if(this.value === 'Name') { this.value = ''; }"
onblur="if(this.value === '') { this.value = 'Name'; }"
value="Name">
<input name="alter" type="text" id="alter" size="3"
onfocus="if(this.value === 'Alter') { this.value = ''; }"
onblur="if(this.value === '') { this.value = 'Alter'; }"
value="Alter">
<input name="email" type="text" id="email" size="30"
onfocus="if(this.value === 'E-Mail') { this.value = ''; }"
onblur="if(this.value === '') { this.value = 'E-Mail'; }"
value="E-Mail">
<input name="phone" type="text" id="phone" size="30"
onfocus="if(this.value === 'Handynummer') { this.value = ''; }"
onblur="if(this.value === '') { this.value = 'Handynummer'; }"
value="Handynummer">
<input name="facebook" type="text" id="facebook" size="200"
onfocus="if(this.value === 'Facebook') { this.value = ''; }"
onblur="if(this.value === '') { this.value = 'Facebook'; }"
value="Facebook">
<input name="instagram" type="text" id="instagram" size="200"
onfocus="if(this.value === 'Instagram') { this.value = ''; }"
onblur="if(this.value === '') { this.value = 'Instagram'; }"
value="Instagram">
</div>
<div class="one_half last">
<textarea name="comments" cols="40" rows="3" id="comments"
onfocus="if(this.value === 'Nachricht') { this.value = ''; }"
onblur="if(this.value === '') { this.value = 'Nachricht'; }">
Nachricht
</textarea>
</div>
<input type="submit" class="send_message" id="submit" value="Senden"/>
</form>
<?php echo $mailResult ?>
</body>
</html>
I would anyway avoid this kind of solution. I would approach this problem with AJAX.
In these solutions, we are mixing the logic with the rendering.
Related
With purpose to save your time I have two screenshots of my contact form.
Also instead of expected result the message "Thank you. Your message has been received" I got in new window. How can I place the message in that input element? Where am I wrong?
You can check my contact form by this link just send any message.
Thank you so much for your time and answers.
<form action="contact/form-handler.php" method="post">
<fieldset>
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" class="form-control" name="name" id="name" placeholder="Your Name"/>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" name="email" id="email" placeholder="Your Email"/>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject"/>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
</div>
<div>
<input type="hidden" name="hidden" value="" />
<div class="nocomment">
<label for="nocomment"></label>
<input id="nocomment" class="nocomment" value="" name="nocomment" />
</div>
<div class="text-center">
<input type="submit" value="Send Message" name="submit"/>
<input type="reset" value="Clear Message" name="reset"/>
</div>
</div>
<input type="hidden" name="v_error" id="v-error" value="Required" />
<input type="hidden" name="v_email" id="v-email" value="Enter a valid email" />
</fieldset>
</form>
And my contact/form-handler.php
<?php
include('SMTPClass.php');
$emailto = 'myemail.com';
// retrieve from parameters
$emailfrom = isset($_POST["email"]) ? $_POST["email"] : "";
$nocomment = isset($_POST["nocomment"]) ? $_POST["nocomment"] : "";
$subject = 'Email from InWebWorld';
$message = '';
$response = '';
$response_fail = 'There was an error verifying your details.';
// Honeypot captcha
if($nocomment == '') {
$params = $_POST;
foreach ( $params as $key=>$value ){
if(!($key == 'ip' || $key == 'emailsubject' || $key == 'url' || $key == 'emailto' || $key == 'nocomment' || $key == 'v_error' || $key == 'v_email')){
$key = ucwords(str_replace("-", " ", $key));
if ( gettype( $value ) == "array" ){
$message .= "$key: \n";
foreach ( $value as $two_dim_value )
$message .= "...$two_dim_value<br>";
}else {
$message .= $value != '' ? "$key: $value\n" : '';
}
}
}
$response = sendEmail($subject, $message, $emailto, $emailfrom);
} else {
$response = $response_fail;
}
echo $response;
// Run server-side validation
function sendEmail($subject, $content, $emailto, $emailfrom) {
$from = $emailfrom;
$response_sent = 'Thank you. Your messsage has been received.';
$response_error = 'Error. Please try again.';
$subject = filter($subject);
$url = "Origin Page: ".$_SERVER['HTTP_REFERER'];
$ip = "IP Address: ".$_SERVER["REMOTE_ADDR"];
$message = $content."\n$ip\r\n$url";
// Validate return email & inform admin
$emailto = filter($emailto);
// Setup final message
$body = wordwrap($message);
// Create header
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\r\n";
// Send email
$mail_sent = #mail($emailto, $subject, $body, $headers);
$response = $mail_sent ? $response_sent : $response_error;
return $response;
}
// Remove any un-safe values to prevent email injection
function filter($value) {
$pattern = array("/\n/", "/\r/", "/content-type:/i", "/to:/i", "/from:/i", "/cc:/i");
$value = preg_replace($pattern, "", $value);
return $value;
}
exit;
?>
If this php code is in contact/form-handler.php than instead of echo $response; you should redirect back to your contact page with the message, like header('Location: contact_page_url?message='.urlencode($response));And in your contact page put below your form:
<script>
function findGetParameter(parameterName) {
var result = null, tmp = [];
location.search.substr(1).split("&").forEach(function (item){
tmp = item.split("=");
if (tmp[0] === parameterName)
result = decodeURIComponent(tmp[1]);
});
return result;
}
document.querySelector('#nocomment').value = findGetParameter('message') || '';
</script>
I'm trying to make $name, $email, and $message validate in one script without making them all look like a error (make them all a red color) rather than the one that is actually incorrect.
Her is the code I'm using:
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'matt.owen#example.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
} else {
exit(json_encode(array('error' => 1)));
}
if ($name == "") {
exit(json_encode(array('error' => 1)));
} else {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
}
?>
AJAX Script:
var sendEmail = function(){
var url = 'main.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) {
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else {
$('#email-input').css('color', 'red');
alert('ERROR MESSAGE');
}
}
})
return false;
}
HTML:
<div id="contact">
<div class="container">
<form id="contact-form" method="post" onsubmit="return sendEmail()">
<h1>Contact Form</h1>
<fieldset>
<input placeholder="Your Name" type="text" name="name" id="name-input" required value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
</fieldset>
<fieldset>
<input placeholder="Your Web Site (optional)" type="url" name="site" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name="message" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>"></textarea>
</fieldset>
<fieldset>
<button type="submit" id="contact-submit" name="submit">Submit</button>
</fieldset>
</form>
</div>
</div>
Just send back a list of bad elements, instead of a blanket error statement
<?php
// ...
$errors = [];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = "email";
}
if ($name == "") {
$errors[] = "name";
}
if ($message == "") {
$errors[] = "message";
}
if (count($errors) === 0) {
mail($to, $email_subject, $email_body,$headers);
}
echo json_encode($errors);
//...
Then in your JS:
success : function(response) {
if (response.length == 0) {
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else {
for (var i = 0; i < response.length; i++) {
$('#' + response[i] + '-input').css('color', 'red');
alert('ERROR MESSAGE');
}
}
}
My Javascript is a bit rusty but that should do the trick.
Note that <textarea> doesn't have a value attribute, contents are added as a child text node. You should also use htmlspecialchars() on all output from PHP to prevent XSS problems.
in your js:
$erro = 0;
if(document.getElementById("name-input").value == null or document.getElementById("name-input").value == ""){
$erro = 1;
document.getElementById("name-input").style.borderColor = "red";
}
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
}
...
if($erro == 0){
//run ajax
}
You can put a bit more html code to make a hidden textbox appear using.
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
document.getElementById("id_erro1").style.visibility = "visible";
}
create in your html:
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
<input type="hidden" name="error_mensage1" id="id_erro1" value="Required field" >
</fieldset>
Use css to Spice up.
I would like people to be able to submit their contact info via a form I have on the site. I have no clue how to code PHP myself, so I snagged a "working model" and made some edits to fit my site. Here is the HTML code:
<form name="contact" method="post" action="formsubmit.php">
<li>
<input name="first_name" type="text" value="first name (Required)" onfocus="if(this.value == 'first name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'first name'; }" />
<input name="last_name" type="text" value="last name (Required)" onfocus="if(this.value == 'last name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'last name'; }" />
<input name="email" type="text" value="email (Required)" onfocus="if(this.value == 'email (Required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'email (Required)'; }" />
<input name="telephone" type="text" value="phone" onfocus="if(this.value == 'phone (Required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'phone'; }" />
<input name="comments" type="text" value="What are your goals?" onfocus="if(this.value == 'What are your goals?') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'What are your goals?'; }" />
<div class="g-recaptcha" data-sitekey="I am using site key here, just wasn't sure if the public should be privy to that info or not"></div>
</li>
</form>
<li>
<input type="submit" value="SUBMIT" class="submitbtn" form="contact" />
</li>
And here is the .php
<!doctype html>
<html>
<head>
<!-- CSS -->
<link href="main.css" rel="stylesheet" type="text/css" />
<meta charset="UTF-8">
<title>We Will EnduroFit</title>
</head>
<body>
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "someone#example.com";
$email_subject = "Message from website visitor";
function died($error) {
// your error code can go here
echo "I am sorry, but there were error(s) found with the form you submitted.";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('I am sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include success html here -->
<h2>Thanks! I will respond to you soon :)</h2>
<?php
}
?>
</body>
</html>
If anyone can take a look at that and tell me what I am missing. The submit button just acts like its dead. It does nothing at all. I know it was working as a model, so I have no idea what I did/did not change to break the stupid submit button. Thanks a million!
Try this: I've change the location of your closing form tag
<form name="contact" method="post" action="formsubmit.php">
<li>
<input name="first_name" type="text" value="first name (Required)" onfocus="if(this.value == 'first name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'first name'; }" />
<input name="last_name" type="text" value="last name (Required)" onfocus="if(this.value == 'last name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'last name'; }" />
<input name="email" type="text" value="email (Required)" onfocus="if(this.value == 'email (Required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'email (Required)'; }" />
<input name="telephone" type="text" value="phone" onfocus="if(this.value == 'phone (Required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'phone'; }" />
<input name="comments" type="text" value="What are your goals?" onfocus="if(this.value == 'What are your goals?') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'What are your goals?'; }" />
<div class="g-recaptcha" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxx"></div>
</li>
<li>
<input type="submit" value="SUBMIT" class="submitbtn" form="contact" />
</li>
</form>
Having some trouble with the contact form on my website, http://www.techcom.co.nz/
It works fine on google chrome, however on IE and Firefox it doesn't send any message and just redirects back up to the top of the page/refreshes the page.
Here is the php code for the form:
// EDIT THE FOLLOWING LINE BELOW AS REQUIRED
$send_email_to = "techcomnz#gmail.com";
function send_email($name,$email,$email_subject,$email_message)
{
global $send_email_to;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>Message = </strong>".$email_message."<br>";
#mail($send_email_to, $email_subject, $message,$headers);
return true;
}
function validate($name,$email,$message,$subject)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['message_msg'] = '';
$return_array['subject'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'enter valid email.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'enter valid name.';
}
}
if($subject == '')
{
$return_array['success'] = '0';
$return_array['subject_msg'] = 'subject is required';
}
if($message == '')
{
$return_array['success'] = '0';
$return_array['message_msg'] = 'message is required';
}
else
{
if (strlen($message) < 2) {
$return_array['success'] = '0';
$return_array['message_msg'] = 'enter valid message.';
}
}
return $return_array;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$return_array = validate($name,$email,$message,$subject);
if($return_array['success'] == '1')
{
send_email($name,$email,$subject,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
and here is the html:
<fieldset id="contact_form">
<div id="msgs"> </div>
<form id="cform" name="cform" method="post" action="">
<input type="text" id="name" name="name" value="Full Name*" onfocus="if(this.value == 'Full Name*') this.value = ''"
onblur="if(this.value == '') this.value = 'Full Name*'" />
<input type="text" id="email" name="email" value="Email Address*" onfocus="if(this.value == 'Email Address*') this.value = ''"
onblur="if(this.value == '') this.value = 'Email Address*'" />
<input type="text" id="subject" name="subject" value="Subject*" onfocus="if(this.value == 'Subject*') this.value = ''"
onblur="if(this.value == '') this.value = 'Subject*'" />
<textarea id="msg" name="message" onfocus="if(this.value == 'Your Message*') this.value = ''"
onblur="if(this.value == '') this.value = 'Your Message*'">Your Message*</textarea>
<button id="submit" class="button" style=""> Send Message</button>
</form>
</fieldset>
Any help would be greatly appreciated.
Regards
Leaving the action attribute blank will cause most browsers to submit the form data to the current page by reloading it with the data in GET or POST.
If this is your intention, try removing the action="" altogether as it has been known to cause issues with older browsers.
I'm using a contact form for my website, which I validate and then email to myself, the validation is working correctly and it emails me if the user enters all the details correctly first time. However if the user enters incorrect data, then corrects it and hits send again, it won't send an email, below is the form and PHP code I have so far.
HTML code for contact form
<form action="contact.php" method="post">
<fieldset>
<label for="name">Name:<span class="star">*</span></label> <br />
<input type="text" name="name" id="name" placeholder="Enter your name" maxlength="50" required />
<label for="email">Email:<span class="star">*</span></label> <br />
<input type="email" name="email" id="email" placeholder="Enter your email address" maxlength="100" required />
<label for="number">Telephone: </label><input type="tel" name="number" id="number" placeholder="Enter your phone number" maxlength="12" />
<label for="message">Message:<span class="star">*</span></label>
<textarea name="message" id="message" placeholder="Enter your message" cols="54" rows="5" required></textarea>
<p class="small"><span class="star">*</span> Denotes a required field </p>
<input type="submit" id="send" name="send" value="Send" />
</fieldset>
</form>
PHP code for sending the form
function fix_string($var)
{
if(get_magic_quotes_gpc()) $var = stripslashes($var);
$var = strip_tags($var);
return $var;
}
{
$details = array('name' => fix_string($_POST['name']),
'email' => fix_string($_POST['email']),
'number' => fix_string($_POST['number']),
'message' => fix_string($_POST['message']));
}
$send = $_POST['send'];
$message = "";
foreach ($details as $field => $detail)
$message .= $field . ": " . $detail . "<br />";
$to = "smokey.12345#hotmail.co.uk";
$subject = "Website contact form";
$message = wordwrap($message, 70, "/r/n");
$headers = "From ". $details['email'];
function trim_value(&$value)
{
$value = trim($value);
}
array_walk($details, 'trim_value');
if ($send)
{
foreach ($details as $field => $detail)
{
if (empty($detail) && $field!='number')
echo "<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>";
}
}
else
{
mail($to, $subject, $message, $headers);
echo "<p class='success'>Mail was sent successfully</p>";
}
EDIT
In order for the code to work on the same page, you need to set the action to action=""
Otherwise, you need to use two pages. One for your form and one for contact.php which is your handler. I suggest you use two pages, but here is a version that will work inside one page.
<?php
if(isset($_POST['send'])) {
function fix_string($var)
{
if(get_magic_quotes_gpc()) $var = stripslashes($var);
$var = strip_tags($var);
return $var;
}
$details = array('name' => fix_string($_POST['name']),
'email' => fix_string($_POST['email']),
'number' => fix_string($_POST['number']),
'message' => fix_string($_POST['message']));
function trim_value(&$value)
{
$value = trim($value);
}
array_walk($details, 'trim_value');
foreach ($details as $field => $detail)
{
if (empty($detail) && $field!='number')
die("<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>");
}
$message = "";
foreach ($details as $field => $detail)
$message .= $field . ": " . $detail . "\n";
$send = $_POST['send'];
$email = $_POST['email'];
$to = "smokey.12345#hotmail.co.uk";
$subject = "Website contact form";
$headers = "From: $email" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($to, $subject, $message, $headers);
echo "<p class='success'>Mail was sent successfully</p>";
exit;
} // closing brace for if(isset($_POST['send'])) {
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<fieldset>
<label for="name">Name:<span class="star">*</span></label> <br />
<input type="text" name="name" id="name" placeholder="Enter your name" maxlength="50" />
<label for="email">Email:<span class="star">*</span></label> <br />
<input type="email" name="email" id="email" placeholder="Enter your email address" maxlength="100" />
<label for="number">Telephone: </label><input type="tel" name="number" id="number" placeholder="Enter your phone number" maxlength="12" />
<label for="message">Message:<span class="star">*</span></label>
<textarea name="message" id="message" placeholder="Enter your message" cols="54" rows="5" ></textarea>
<p class="small"><span class="star">*</span> Denotes a required field </p>
<input type="submit" id="send" name="send" value="Send" />
</fieldset>
</form>
</body>
</html>
Original answer
This line is not properly formatted.
$message = wordwrap($message, 70, "/r/n");
change it to:
$message = wordwrap($message, 70, "\r\n");
You need to use \ instead of /
EDIT
The only way I could get your form to work, is to add a die function.
Try this now:
<?php
function fix_string($var)
{
if(get_magic_quotes_gpc()) $var = stripslashes($var);
$var = strip_tags($var);
return $var;
}
$details = array('name' => fix_string($_POST['name']),
'email' => fix_string($_POST['email']),
'number' => fix_string($_POST['number']),
'message' => fix_string($_POST['message']));
function trim_value(&$value)
{
$value = trim($value);
}
array_walk($details, 'trim_value');
foreach ($details as $field => $detail)
{
if (empty($detail) && $field!='number')
die("<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>");
}
$message = "";
foreach ($details as $field => $detail)
$message .= $field . ": " . $detail . "\n";
$send = $_POST['send'];
$email = $_POST['email'];
$to = "smokey.12345#hotmail.co.uk";
$subject = "Website contact form";
$headers = "From: $email" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($to, $subject, $message, $headers);
echo "<p class='success'>Mail was sent successfully</p>";
exit;
?>