Email form not sending - javascript

I"m having trouble getting this email form to submit. The email.php file is in the root directory and looks like this:
<?php
$val= $_POST['val'];
$toemail='someone#gmail.com';
$name = $val['name'];
$email = $val['email'];
$msg = $val['msg'];
$subject = 'Message from zachjanice.com';
$headers = "From: zachjanice.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<b>Name :</b>".$name."<br>";
$message .='<b>Email :</b>'.$email."<br>";
$message .='<b>Message :</b>'.$msg;
mail($toemail, $subject, $message, $headers);
echo "Thanks for contacting me!";
?>
I'm using validate.js to validate the form and bootstrap to style. Here is the HTML:
<form class="contactform" role="form">
<div class="form-group">
<label class="control-label">Name</label>
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label">Email</label>
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" class="form-control" id="email" name="email" placeholder="Email">
</div>
</div>
</div>
<div class="form-group ">
<label class="control-label">Message</label>
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea name="msg" class="form-control " rows="4" cols="78" placeholder="Enter your message here"></textarea>
</div>
</div>
</div>
<div class="controls" style="margin-left: 40%;">
<button type="submit" id="mybtn" class="btn btn-primary">Send Message</button>
</div>
</form>
I forgot here is my JS:
$(document).ready(function(){
$.validator.setDefaults({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "email.php",
data: { 'val':$(".contactform").serializeJSON() }
}).done(function(data) {
alert(data);
});
}
});
$(".contactform").validate(
{rules:
{name:"required",
email:{required:true,email:true},
website:{required:false,url:true},
cate:"required",
msg:{required:true, maxlength:300
}},
errorClass:"error",
highlight: function(label) {
$(label).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function(label) {
label
.text('Seems Perfect!').addClass('valid')
.closest('.form-group').addClass('has-success');
}
});
});
Help is greatly appreciated. I'm trying to get this site done tonight if possible, but I'm a little flustered at this point.

Try to var_dump(mail($toemail, $subject, $message, $headers));
You'll get some useful info.
Also check if vars $name, $email and $msg are populated, if not do it like this: $name = $_POST['name']

Related

posting data from javascript to php is not working

I'm writing a code that sends email from php with an attachment. And here is my code.
my main.php file
<form action="javascript:postData()" id="form">
<fieldset>
<!-- Form Name -->
<legend>Application</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Full Name">Full Name</label>
<div class="col-md-4">
<input id="FullName" name="FullName" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Email">Email</label>
<div class="col-md-4">
<input id="Email" name="Email" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="roleFor">Role Applying for</label>
<div class="col-md-4">
<input id="roleFor" name="roleFor" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="jobId">Job ID</label>
<div class="col-md-4">
<input id="jobId" name="jobId" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="uploadResume">Upload Resume</label>
<div class="col-md-4">
<input type="file" name="file" class="form-control">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="experience">Experience</label>
<div class="col-md-4">
<textarea class="form-control" id="experience" name="experience"></textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" type="submit" name="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
and my js is
function postData() {
const form = document.getElementById('form');
const data = new FormData();
data.append('FullName', form.FullName.value);
data.append('Email', form.Email.value);
data.append('roleFor', form.roleFor.value);
data.append('jobId', form.jobId.value);
data.append('experience', form.experience.value);
fetch('sendEmail.php', {method: 'POST', body: data}).then(response => {
if (!response.ok){
throw new Error('Network response was not ok.');
} else
{
console.log(response);
alert('New job posted');
document.getElementById("form").reset();
}
}).catch(err => console.log(err));
}
and my sendEmail.php is
<?php
$fName = $_POST['FullName'];
$emailAddr = $_POST['Email'];
$roleFor = $_POST['roleFor'];
$jobId = $_POST['jobId'];
$exp = $_POST['experience'];
if (!empty($fName) && !empty($emailAddr))
{
$statusMsg = '';
if (isset($_FILES["file"]["name"]))
{
$emailAddr = $_POST['Email'];
$fromemail = 'admin#admin.com';
$subject = 'Teesst Syubect';
$email_message = "<table><tr><td>Name: </td><td>" . $fName . "</td></tr> </table>";
$email_message .= "Please find CV in the attachment";
$semi_rand = md5(uniqid(time()));
$headers = "From: " . $fromemail;
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
if ($_FILES["file"]["name"] != "")
{
$strFilesName = $_FILES["file"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n";
$email_message .= "--{$mime_boundary}\n" . "Content-Type: application/octet-stream;\n" . " name=\"{$strFilesName}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $strContent .= "\n\n" . "--{$mime_boundary}--\n";
}
$toemail = "myEmail#gmail.com";
if (mail($toemail, $subject, $email_message, $headers))
{
$statusMsg = "Email send successfully with attachment";
header("Location:careers.php");
}
else
{
$statusMsg = "Not sent";
}
}
}
else
{
echo "Enter both Title and Desription";
die();
}
?>
Now the issues are,
when I do <form action="sendEmail.php" id="form" method="post">, it is sending the email as expected, but when I try to post it through javascript (as shown in my code), it isn't sending an email, but to my surprise, the response status is 200 OK.
Please let me know where I'm going wrong.
Thanks

Contact us form isn't sending all populated fields to email, only a few? PHP AJAX JS

So I've gone through a thread that helped me build this contact us form, but it talked about validating and making the fields required. There are two fields I have in my form that doesn't need to be required $organization and $budget, I can't seem to get the information in there to send with the email. The email shows those fields as blank but the other fields are populated.
I have practically zero experience in PHP outside of this form.
Expected output:
Name: xxx
Email: xxx#xxx.com
Organization: xxx
Budget: xxx
Message: xxx
What I actually receive in my email:
Name: xxx
Email: xxx#xxx.com
Organization:
Budget:
Message: xxx
Code:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// Organization
$organization = $_POST["organization"];
// Budget
$budget = $_POST["budget"];
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "example#mydomain.com";
$Subject = "Received msg from WIP contact form";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Organization: ";
$Body .= $organization;
$Body .= "\n";
$Body .= "Budget: ";
$Body .= $budget;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Sorry, something went wrong.";
} else {
echo $errorMSG;
}
}
?>
HTML:
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="organization" class="h4">Organization</label>
<input type="text" class="form-control" id="organization" placeholder="Enter organization">
<div class="help-block with-errors"></div>
</div>
<div class="form group col-sm-6">
<label for="budget" class="h4">Budget</label>
<input type="number" class="form-control" id="budget" placeholder="$50000">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="button pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JavaScript:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Please fill in the required fields.");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var organization = $("#organization").val();
var budget = $("#budget").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message + "&organization=" + organization + "&budget" + budget,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "We'll be in touch with you soon!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
EDIT
Thanks to Uxmal for suggesting the name="xxxx" in the input field. He said that by doing this, the $_POST is looking for inputs with name. Which made me realise I must be doing something else wrong. Turns out my ajax was poorly written and I was also missing the <form action aswell. Below is the corrected version of the form and ajax code.
<form action="form-process.php" method="POST" role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label for="organization" class="h4">Organization</label>
<input type="text" class="form-control" id="organization" name="organization" placeholder="Enter organization name">
<div class="help-block with-errors"></div>
</div>
<div class="form group col-sm-6">
<label for="budget" class="h4">Budget</label>
<input type="number" class="form-control" id="budget" name="budget" placeholder="50000">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" name="message" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="button pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JS:
function submitForm(){
$.ajax({
type: "POST",
url: "php/form-process.php",
data: $('#contactForm').serialize(),
success: function(text) {
if (text == "success") {
formSuccess();
} else {
formError();
submitMSG(false, text);
}
}
});
}
You PHP code at line
// Organization
$organization = $_POST["organization"];
// Budget
$budget = $_POST["budget"];
looks for inputs with name: organization and budget, no to for id organization and budget.
At you html is
<input type="text" class="form-control" id="organization" placeholder="Enter organization">
<input type="number" class="form-control" id="budget" placeholder="$50000">
without a tag: name="organization" and tag: name="budget".
So put those tags like
<input type="text" class="form-control" id="organization" name="organization" placeholder="Enter organization">
<input type="number" class="form-control" id="budget" name="budget" placeholder="$50000">
and then your PHP code will get the data.

How do I creat a jquery form validator

I am trying to create a dynamic website using php. The site is uploaded to a free domain this is my first real world project so I want to put in as best as I can. I created a modal, in it there is a form and I want this from to validate and without refreshing the page. but I don't know why my mail() is not working please can someone tell me what I am doing wrong.
This is my fixed form inside the modal:
<div class="modal fade" id="myModal" tabindex="-1" role="form" aria-labelledby="#modalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title " id="modalLabel">Send
<?php echo
$brandName; ?> a message</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="thumbnail">
<form action="contact_process.php" method="POST" role="form" autocomplete="off" class="form-container">
<small>
<i class="text-center
text-danger">all fields are required</i>
</small>
<div class="form-group has-danger">
<label class="sr-only" for="name">Name
</label>
<input type="text" name="name" placeholder="Your Name" class="form-control" id="mail-name" tabindex="1">
</div>
<div class="form-group has-danger">
<label class="sr-only" for="email">Email
</label>
<input type="email" name="email" placeholder="Your E-mail" class="form-control" id="mail-email" tabindex="2">
</div>
<div class="form-group has-danger">
<label for="tel" class="sr-only">Tell
no.
</label>
<input type="text" name="phone" placeholder="Your Phone Number" class="form-control" id="mail-
phone" tabindex="3">
</div>
<div class="form-group has-danger">
<label for="message" class="sr-only">
</label>
<textarea class="form-control
form-textarea" placeholder="Message" rows="5" spellcheck="true" name="message" id="mail-message" tabindex="4"></textarea>
</div>
<input type="button" class="btn
btn-danger" data-dismiss="modal" aria-label="Close" value="Cancel" tabindex="5">
<input id="mail-submit" type="submit" class="btn btn-primary" value="Send Message" name="submit" data- submit="...Sending" tabindex="6">
<p class="form-msg"></p>
</form>
</div>
<!--END thumbnail-->
</div>
<!--END col-->
</div>
<!--END row-->
</div>
<!--modal-body-->
</div>
<!--modal-content-->
</div>
<!--modal-dialog-->
</div>
<!---modal-->
This is the php form validation in my includes folder:
<pre>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmail = false;
$errorPhone = false;
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
echo "<span class='err'>Fill in all fields!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='err'>Invalid email please make sure you enter a
valid email address!</span>";
$errorEmail = true;
}
elseif (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?
\d{3}[\s-]?\d{4}$/i",$phone)) {
echo "<span class='err'>Please enter only a valid phone number!
</span>";
$errorPhone = true;
}
else{
// add resipeants
$to = "danjumashiwaju#gmail.com";
// create subject
$subject = "$name sent you a message from www.djshumzy.com";
// construct a message
$msg = "Name: $name\r\n";
$msg .= "Email: $email\r\n";
$msg .= "Tell: $phone\r\n";
$msg .= "Message: \r\n$message";
$msg = wordwrap($meg, 70);
//set mail header
$headers = "MINE-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=1so-8859-1\r\n";
$headers .= "From: $name <$email>\r\n";
$headers .= "X-priority: 1\r\n";
$headers .= "X-MSMail-priority: High1\r\n\r\n";
mail( $to, $subject, $msg, $headers);
} if (mail === 1) {
echo "<span class='suc'>Thank You!...Your Message has been Sent !
</span>";
}
}
?>
<script>
$("#mail-name, #mail-email, #mail-phone,
#mail-message").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var errorPhone = "<?php echo $errorPhone; ?>";
if (errorEmpty == true) {
$("#mail-name, #mail-email, #mail-phone,
#mail-message").addClass("input-error");
}
if (errorEmail == true) {
$("#mail-email").addClass("input-error");
}
if (errorPhone == true) {
$("#mail-phone").addClass("input-error");
}
if (errorEmpty == false && errorEmail == false && errorPhone == false) {
$("#mail-name, #mail-email, #mail-phone, #mail-message").val("");
}
</script>
</pre>
Here is my jquery validation(.js)
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-msg").load("includes/contact_process.php", {
name: name,
email: email,
phone: phone,
message: message,
submit: submit
});
});
});// END FORM VALIDATING
Please what do I have to do to make this from submit to emails and validate at the same time.
Thus the form validates but it does not send the email and just gives an error message instead.
Use https://jqueryvalidation.org/
$( "#myform" ).validate({
rules: {
field: {
required: true
},
email: {
required: true,
email: true
}
},
messages: {
field: "Please Enter Your Name",
email: "Please Enter Your Email Address"
}
});
<link href="https://jqueryvalidation.org/files/demo/site-demos.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="myform">
<label for="field">Enter Name : </label>
<input type="text" class="left" id="field" name="field">
<br/>
<label for="email">Email Address: </label>
<input type="text" id="email" name="email">
<br/>
<input type="submit" value="Validate!">
</form>
This jQuery plugin makes simple clientside form validation easy.

Ajax sending data from other php file contact form

I am new to AJAX, i came from a code in internet about sending Ajax to php file. The problem is i dont know if the data is submitted or what happen. The alert box doesn't pop up if it was submited
success: function () {
alert('form was submitted');
}
Here is the full form from html :
<form class="form-horizontal">
<div class="form-group">
<label for="contact-name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="name" name="name" placeholder="FULL Name" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<label for="contact-msg" class="col-sm-2 control-label">Message</label>
<div class="col-sm-4">
<textarea name="message" class="form-control" required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-primary" type="submit" value="submit" >Send Message</button>
</div>
</div>
</form>
here is the script :
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'mail.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
and because i dont know where the problem is, please check also my php code. thank you stackoverflow,good programmers.
php code :
<?php
$name = $_POST['name'];
$email_from = $_POST['email'];
$comments = $_POST['message'];
$email_to = "jcjohn#gmail.com";
$email_subject = "Message from John Web";
$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 .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\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);
echo "<script type='text/javascript'>alert('$message');</script>";
?>
am i doing right ? or maybe i was doing something that nothing goes.
Kindly Use ajaxForm Plugin and include jquery library.I think this will work fine for you.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function(data) {
alert(data);
});
});
</script>
</head>
<body>
<form id="myForm" action="comment.php" method="post">
<div class="form-group">
<label for="contact-name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="name" name="name" placeholder="FULL Name" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<label for="contact-msg" class="col-sm-2 control-label">Message</label>
<div class="col-sm-4">
<textarea name="message" class="form-control" required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-primary" type="submit" value="submit" >Send Message</button>
</div>
</div>
</form>
</body>
</html>
and your PHP file code must be like this
<?php
$name = $_POST['name'];
$email_from = $_POST['email'];
$comments = $_POST['message'];
$email_to = "jcjohn#gmail.com";
$email_subject = "Message from John Web";
$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 .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\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);
echo "Form Submitted";
?>

Ajax not posting form data

I recently asked a question about executing a Send Mail script without a page reload and worked out what my problem was with my AJAX, that's all resolved. I now have an issue with the following:
When my form posts to my AJAX the script is executed, however the post data doesn't seem to be come through to the PHP script.
The link to my question is: Contact Form same page success.
Here is my PHP:
<?php
$name = ($_POST['name']);
$email = ($_POST['email']);
$fsubject = ($_POST['subject']);
$message = ("Name: ". $name . "\nEmail Address: " . $email . "\n\nMessage: " . $_POST['message']);
// Set Mail
$to = "emailaddress#fakeone.com";
$header = 'From: contactus#fakeone.com' . "\r\n" .
'Reply-To: website#fakeone.com';
$subject = "{$fsubject}";
$body = "{$message}";
// Send Mail
if (mail($to, $subject, $body, $header))
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>
My HTML
<div id="success" style="color:red;"></div>
<form action="" id="contactform" method="post">
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Your name *</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name">
</div>
<div class="col-md-6">
<label>Your email address *</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Subject</label>
<input type="text" value="" data-msg-required="Please enter the subject." maxlength="100" class="form-control" name="subject" id="subject">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Message *</label>
<textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" id="submit" value="Send Message" class="btn btn-info btn-lg" data-loading-text="Loading...">
</div>
</form>
My AJAX
<script>
$(document).ready(function () {
$('#submit').click(function () {
$.post("sendmail.php", $("#contactform").serialize(), function (response) {
$('#success').html(response);
});
return false;
});
});
</script>
When I fill out the forms, nothing comes back it sends an empty email.
Any idea's why the post isn't working on this would be greatly appreciated. If I am breaking any rules by posting another question please let me know!
Regards,
Dan
I think the problem is in your PHP code. You've got a variable named $headers, but in your mail function you're using $header. A typo.
Change the following lines from this -
$subject = "{$fsubject}";
$body = "{$message}";
to this -
$subject = $fsubject;
$body = $message;

Categories

Resources