AJAX send text in only one line - javascript

I have a problem with an ajax request.
I have a form that has two text input and a textarea and an ajax function that sends to another page called mail.php the text of the three input, then mail.php sends an e-mail with those data and return 1 if the e-mail was sent correctly and 0 if not. It works but in the arrived e-mail the text is only in one line also if in the textarea i have got 3 or 4 line.
This is the form:
<div id="form">
<input type="email" class="style" id="mail" maxlength="80" placeholder="Inserisci la tua e-mail" required />
<br>
<input type="text" class="style" id="subject" maxlength="50" placeholder="Oggetto" required />
<br>
<textarea id="message" class="style" placeholder="Scrivi il messaggio..." rows="8" maxlength="2000" required></textarea>
<br>
<button type="submit" id="submit_button"><div><p class="send_button_content">Invia</p><img id="send_button_icon" class="send_button_content" src="send_icon.png"></div></button>
</div>
And this is the ajax function:
function sendEmail(){
var mail;
var subject;
var message;
mail = $("#mail").val();
subject = $("#subject").val();
message = $("#message").val();
if (mail !="" && subject !="" && message !="") {
if (emailCheck(mail)){
$.post("mail.php",{mail: mail,subject: subject,message: message},function(data){alert(data);});
}else{
alert("The e-mail is not correct")
}
} else {
alert("Fill all");
}
}
$("#submit_button").click(function(){sendEmail(); });
And mail.php is like this:
$mail = $_POST['mail'];
$subject = "Nuovo messaggio: ".$_POST['subject'];
$message = "<html>
<head>
</head>
<body>
<p>New message from: ".$mail."<br>
Message: ".$_POST['message']."<br>
<a href='mailto:".$mail."?subject=".$_POST['subject']."' style='color:blue' target='_blank'>Reply here</a>
</p>
</body>
</html>";
if($mail != "" && $subject != "" && $message != ""){
$to = "***********#gmail.com";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$result = mail($to,$subject,$message,$headers) or die('0');
if(result){
die('1');
}else{
die('0');
}
}else{
die('0');
}
Is there a method that take the text as I have written and send it?

use nl2br()
$message=nl2br($_POST['message']);

Related

Data from new HTML form input field not being passed to email using PHP and JavaScript

This is my first post on the site. I added a new input field to a previously working HTML contact form in order to collect the user’s street address. Although all other input fields continue to pass data to the email generated after the form is submitted, data is not being passed to the email with the street address. I have copied below the associated HTML, PHP, and JavaScript files, as well as an example of what data is now sent to the email.
I truly appreciate any help with what I am doing wrong. I have spent over 8 hours trying to solve this problem, but so far have been unsuccessful. Thank you!
Here is an example of the data now being placed into the email generated. Notice that the only data NOT being passed is the text that was input into the street address field of the contact form (blank).
Name: Tim Spyridon
Address:
Phone Number: 513-662-1464
Message:
Made major changes to PHP script. This may work!
Here is the HTML code used for the contact form:
<!-- Form Starts -->
<div id="contact_form">
<div class="form-group">
<label>Name <span class="required">*</span></label>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required>
<label>Street Address and City <span class="required">*</span></label>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required>
<label>Email Address <span class="required">*</span></label>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required>
<label>Phone Number including Area Code <span class="required">*</span></label>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required>
<label>Message <span class="required">*</span></label>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required></textarea>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
Here is my JavaScript code from a file called contact.js:
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('php/sendmail.php', post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
//reset values in all input fields
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
Here is my PHP script from a file called sendmail.php:
<?php
if($_POST)
{
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die($output);
}
}
?>
In support of the comment made last night (above ) here is the test version of the above script which appears to work perfectly well in terms of the newly added message field. There are comments at places where things were changed - some semantic, others functional.
<?php
if( $_POST ){
# Simple Boolean to switch between live & test mode
# whilst testing that this script does or does not
# function correctly.
$b_live=false;
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if( !isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) AND strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) != 'xmlhttprequest' ) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
# If the script is live, attempt to send the emails
if( $b_live ){
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
}else{
# emulate either a success or failure randomly
# to aid testing of ajax callback
$send_mail=mt_rand(0,1);
# you can verify the message is being populated
$_POST['MESSAGE']=$message;
$_POST['TIME']=date( DATE_ATOM );
file_put_contents( __DIR__ . '/ajax.log', json_encode( $_POST ) . PHP_EOL, FILE_APPEND );
}
if(!$send_mail){
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die( $output );
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die( $output );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Contact</title>
</head>
<body>
<!--
The `label` attribute **must** be associated with whichever form element
it is supposed to reference. This can be done either by including the
`for` attribute in the label with the input element's ID OR the form element
must be within the label itself - as shown below.
-->
<div id="contact_form">
<div class="form-group">
<label>
Name <span class="required">*</span>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required />
</label>
<label>
Street Address and City <span class="required">*</span>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required />
</label>
<label>
Email Address <span class="required">*</span>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required />
</label>
<label>
Phone Number including Area Code <span class="required">*</span>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required />
</label>
<label>
Message <span class="required">*</span>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required /></textarea>
</label>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
<!--
Added this DIV to allow output to be rendered
-->
<div id='contact_results'></div>
<script>
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
/*
*****************************************************
This is the ONLY change made in the Javascript
*****************************************************
*/
const _URL=location.href; // 'php/sendmail.php'
$.post( _URL, post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
</script>
</body>
</html>
With this I could not replicate the issues stated in the question: The $message variable is populated and can be inspected in the console or the ajax.log file that is generated in test mode.

Message returning object HTMLSpanElement in email

Whenever i use a contact form on my website, everything is working fine except message. It is returning [object HTMLSpanElement]
Here is my code of mail.js i have created separate files because i am also using this file for error handling.
function submit_form()
{
var letters = /^[A-Za-z]+$/;
var message = document.getElementById('subject').value;
$.ajax({
type:'post',
url:'enquiry.php',
data:'name='+name+'&email='+email+'&contactno='+contactno+'&message='+message1,
success:function(data)
{
if(data=="1")
{
//document.getElementById('success').innerHTML="Your message has been sent successfully.";
$('#success').html("Your message has been sent successfully.")
and here is the code of enquiry.php
$name = $_POST['name'];
$email = $_POST['email'];
$contactno = $_POST['contactno'];
$message1 = $_POST['message'];
$to = "emailaddress#email.com";
$subject = "Enquiry";
$from = "emailaddress#email.com";
$message = "
<html>
<head>
<title>ENQUIRY</title>
</head>
<body>
<h4>ENQUIRY</h4>
<b>Full Name</b>: $name<br />
<b>Email Id</b>: $email<br />
<b>Contact</b>: $contactno <br />
<b>Message </b>: $message1<br />
</body>
</html>";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <".$from. ">" ;
if(mail($to,$subject,$message,$headers))
{
echo 1;
}
And here is the html for that
<input type="text" name="contactno" maxlength="10" pattern="[1-9]{1}[0-9]{9}" id="contactno" placeholder="Enter 10 digit Contact Number" class="footer-form1" value="" onchange="removeerr();" required><br>
<span id="contact1"></span>
<textarea id="subject" name="message" id="subject" placeholder="Write your message here.." class="footer-massage" value="" onchange="removeerr();" required></textarea>
<span id="message1"></span>
<span id="success"></span>
When you send the data with:
data:'name='+name+'&email='+email+'&contactno='+contactno+'&message='+message1,
message1 is a reference to the HTML span element with that id. Your message appears to be inside of the textarea element with an id of subject and you are correctly getting that data and storing it, but you are calling your variable message (not message1), so the line that sends the data should be:
data:'name='+name+'&email='+email+'&contactno='+contactno+'&message='+message,

Ajax/php contact form sending blank emails from time to time

Well I have this contact form that sends blank emails. But I did some testing and it doesn't happens to me. The only way this could happen, I think, would be by accesing the .php file directly. If not I don't know what could be the problem. The form doesn't let you send a blank email. If this keeps happening I'm going to add a validation in the php file too, but until I find out what is the problem I don't want to ignore this messages.
This is the HTML
<form name="contactForm" id="contactForm" method="post" action="/contactEngine.php" onsubmit="return validateForm()">
<input title="Input name" type="text" name="Name" id="Name" placeholder="Nombre:" required="">
<input title="Input email" placeholder="Email:" type="email" name="Email" id="Email" required="">
<input type="text" placeholder="Subject:" name="Subjet" id="Subjet">
<textarea title="Input message" placeholder="Mensaje:" name="Message" rows="20" cols="20" id="Message" required=""></textarea>
<input title="Input result" placeholder="25 + 25 = ?" type="text" name="Captcha" id="Captcha" required="">
<p id="wrongCaptcha"> Try again </p>
<input type="submit" name="submit" value="send" class="submit-button">
</form>
This is the JS
function validateForm(e) {
e.preventDefault();
var x = document.forms["contactForm"]["Captcha"].value;
if (x != 50) {//if captcha is wrong
$("#Captcha").addClass("wrongCaptchaEntered");
$("#Captcha").css("animation-name" , "none");
setTimeout (function(){
$("#Captcha").css("animation-name" , "changeBorder");
},100);
if ($("#wrongCaptcha").css("display") == "none"){
$("#wrongCaptcha").slideDown();
}
}
else { //if captcha is correct
var formAction = $("#contactForm").attr("action");
if (formAction == "/contactEngine.php"){
var formData = $("#contactForm").serialize();
$.post( formAction, formData, function(data){
console.log (data);
$(".formulario").changeTo({content: "<h2 class='section-title BackgroundGradientBlack'>"+ data +"</h2>"});
});
}
}
return false;
}
And the PHP
<?php
$EmailFrom = "EmailFrom#test.com";
$EmailTo = "EmailTo#test.com";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Subject = Trim(stripslashes($_POST['Subjet']));
$Message = Trim(stripslashes($_POST['Message']));
$email_content = "Frontpage";
$email_content .= "\nNombre: $Name";
$email_content .= "\nEmail: $Email";
$email_content .= "\nMotivo: $Subject";
$email_content .= "\nMensaje: $Message";
$email_headers = "From: <$EmailFrom>";
if (mail($EmailTo, $Subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Mensaje enviado";
} else {
http_response_code(500);
echo "Error";
}
?>
Thanks!
Probably some bot that's testing the PHP endpoint it can see in your JS and is sending data to it, trying to cause havoc. I bet if you logged the $_POST variable every time an email was sent, you'd seen a lot of spammy nonsense in some $_POST variables. Emails are blank just because the bots aren't smart enough to know which keys to use in its POSTs.

PHP contact form will just refresh the page after submission.

After searching for about 3 hours i still can't figure this one out.
I Have a html template with a contact form and im trying to make it work using a PHP script.
I changed the template to PHP and pasted the PHP form script in it. everything is working fine except the confirmation text.
After a successful submission it will just refresh the page instead of printing "Your mail has been sent successfuly ! Thank you for your feedback". i do not want a redirect, i just want it to print on the same page.
Any ideas?
I got a sample of my code.
<form action="<? echo $_SERVER['PHP_SELF']; ?>" id="contact-form" method="post" class="form afsana-form" role="form">
<div class="row">
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="name" name="name" placeholder="name" type="text" required autofocus />
</div>
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="email" name="email" placeholder="email" type="email" required />
</div>
<div class="col-sm-12 form-group">
<textarea class="form-control" id="message" name="message" placeholder="message" rows="5"></textarea>
</div>
<div class="col-sm-12 form-group">
<button class="btn btn-primary afsana-btn" name="submit" value="verzenden" type="submit">Verzenden <i class="ion-arrow-graph-up-right"></i></button>
</div>
</div>
</form>
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$subject = (Contact_form);
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("something#domain.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
First, you have this: $subject = (Contact_form); which should throw an error, so I assume you have error reporting turned off. When developing, you should have error reporting on so you can see errors in your code... Else you are just working blind. I don't mean by throwing tacky error_reporting(0) in every file either, I mean to set your error reporting level to E_ALL in your php.ini.
You also have: $headers .= 'Cc:'. $email2 . "\r\n";
However, $email2 is not defined anywhere, so you would get an error here too.. which is why it's important to test with error reporting on.
See if this works:
<?php
$error = '';
if(isset($_POST['submit']))
{
if ( !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']) )
{
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( $email = filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$subject = '(Contact_form)';
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$message = wordwrap($message, 70);
if ( $result = mail("something#domain.com", $subject, $message, $headers) ) {
$error = 'Success';
} else {
$error = 'There was an error sending your email!';
}
} else {
$error = 'Invalid Email Address!';
}
} else {
$error = 'Please fill all fields.';
}
}
?>
<p><?= $error ?></p>
<form action="" method="post">
<input type="text" name="name" value="" /><br />
<input type="email" name="email" value="" /><br />
<textarea name="message" rows="5"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
Try to put in $subject just a string value like:
$subject = 'Test subject';
change also the following line to this (there is no $email2 defined):
$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
and give it a try. You can also put as first line of your code
<?php error_reporting(E_ALL); ?>
and check for errors when submiting the form.

Contact form - cannot get email to send

I am trying to create a basic form to send an email and here is how it looks:
http://www.unitedserbians.com/contact_us.html
I have everything working and buttoned up, except I cannot get the actual email to be sent once the form has completed processing. My function executes as my field validations work great and I can see the correct values are being grabbed from the form by un-commenting the JAVA script code "alert (dataString);return false;" and even the .ajax executes because I get "Contact Form Sent! We will be in touch soon." message displayed but the actual email never gets sent. I am guessing that something is missing in the process.php file. I cannot trace to see where the issue occurs or if my process.php ever executes. Should the file live in the same directory with JAVA script? or at main directory bin folder? Or is there something I am blindly missing in the process code? Can someone spot what am I missing please? Much appreciated in advance.
HTML:
<div class="content">
<div class="content_resize">
<div class="mainbar">
<div class="article">
<h2><span>Send us E-Mail</span></h2>
<div id="contact_form">
<form action="" form name="contact">
<fieldset>
<ol>
<li>
<label for="name" id="name_label">Your Full Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label2 class="error" for="name" id="name_error">This field is required.</label2>
</li>
<li>
<label for="email" id="email_label">Your Email Address</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label2 class="error" for="email" id="email_error">This field is required.</label2>
</li>
<li>
<label for="website id="phone_label">Your Phone Number</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label2 class="error" for="phone" id="phone_error">This field is required.</label2>
</li>
<li>
<label for="message">Your Message</label>
<textarea id="message" name="message" rows="8" cols="50"></textarea>
</li>
<li>
<input type="submit" name="imageField" id="submit_btn" src="images/submit.gif" class="send" />
</li>
</ol>
</fieldset>
</form>
</div>
</div>
</div>
JAVA script:
$(function() {
$('.error').hide();
$(".send").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label2#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label2#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label2#phone_error").show();
$("input#phone").focus();
return false;
}
var message = $("textarea#message").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// alert (dataString);
// return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='send_message'></div>");
$('#send_message').html("<h2>Contact Form Sent!</h2>")
.append("<p>We will be in touch soon.</p>");
}
});
return false;
});
});
PHP:
<?php
$email_to = "XXXXX#gmail.com";
$email_subject = "Message sent using contact form.";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$message = $_POST['message'];
$email_message .= "Full Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Phone Number: ".clean_string($phone)."\n";
$email_message .= "Message: ".clean_string($message)."\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);
?>
One possibility is that your host doesn't like the $email_from address. I think most hosts are restrictive about sending using a From address that isn't associated with that host (this is so to not enable spammers). Try using no-reply#yourdomain.com or something like that, or even better an address that really exists, as your From address. The Reply-To can still be the address the user enters (after you check that it is valid).

Categories

Resources