I am trying to send email in PHP using AJAX in a simple contact form. I have the following codes for a simple form, PHP code for submit button and AJAX script.
When I am trying to send email it is not sending any email and always firing the AJAX error msg. I am not very well in AJAX integration with PHP.
Below is my code
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
I would move the php part to another file:
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
And in another email.php
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
You must be stop the default flow of that form by using event.preventDefault(); and you can pass the form as multipart/formdata or form-data and check the developer tools -> network -> fetch/xhr -> payload/ formdata. then you create a seperate page in php and do the mail process in that page and change the form action link to that page
In html
<form method="post" class="myform" action="mail.php">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).on('submit', '.myform', function(e){
e.preventDefault();
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: new FormData($(".myform")[0]),
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
if (result.status == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
</script>
In php - mail.php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
if($send_email)
{
$response = ['status' => 'success'];
}
else
{
$response = ['status' => 'error'];
}
echo json_encode($response);
}
So, the top answer works, but as #Mithu said, for some reason it always says:
'Error Sending email!'
After 30 minutes of exploring the situation I understood that for some reason it returns from PHP not 'success' but ' success' with 2-4 spaces in front of the word 'success' or 'error'.
So, all you need is to exclude these spaces, for that we need to change 'succes' to 'this is success' and 'error' to 'this is error'(just to make spare letters in the front) and then we need to divide this string to words and to extract the last word. It will always be 'success' or 'error' regardless how much spaces the script will add or how much letters it will remove accidentally. And also you need to make another if else statement in the PHP to check FALSE instead of TRUE.
Also I've added a few lines which check if the fields are filled or not. And if they are not filled then you get a message 'Please fill in the forms.'.
So here how it looks and works for me:
Importing jquery library (you need to place it into the header):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
HTML (you need to put it there where you want to have the contact form):
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
JS (you need to put it in the footer):
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
// if it can't find email.php just chahge the url path to the full path, including your domain and all folders.
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
let d = result.split(" ");
let y = d.slice(-1)[0];
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
if (y == 'success'){
$('.output_message').text('Message Sent!');
}
else if (y == 'miss'){
$('.output_message').text('Please fill in all the fields above.');
}
else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
email.php (you need to create this file in the same folder where you have your index.php):
<?php
// here we check if all fields are filled.
$required = array('name', 'email', 'message');
$error = false;
foreach($required as $field) {
if (empty($_REQUEST[$field])) {
$error = true;
}
}
//if something is not filled(empty) and error is true
if ($error) {
echo 'this is miss';
}
// if everything is filled then we execute the mail function
else {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$fullmessage = "Sender's name: ".$name."\n"."Message: \n".$message;
// Set your email address where you want to receive emails.
$to = 'contact#yourdomain.com';
$subject = 'Message from YOUR E-MAIL.COM';
$send_email = mail($to,$subject,$fullmessage,$email);
if ($send_email == false) {
echo 'this is error';
} else {
echo 'this is success';
}
}
?>
So,this code steadily works for me, but maybe it is not very proffessionaly made, because I am a begginer in JS and PHP.
Related
Update: Final working code is at the very bottom of question I left the rest of the code so you can see the process hope it helps someone in the future.
I am trying to send an email to myself (which is working) using only jQuery and an external php file, however, the email isn't picking up any of the data. I have the following code.
HTML
<section>
<form enctype="multipart/form-data">
<fieldset class="margin-b">
<legend>Contact Me</legend>
<label for="form_name">Name:<input name="form_name" id="form_name" type="text" value="" required autofocus ></label>
<label for="form_email">Email:<input type="email" name="form_email" id="form_email" value=""></label>
<label for="form_msg">Message:<textarea name="form_msg" id="form_msg" rows="5"></textarea></label>
</fieldset>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</section>
JS
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#form_message").val()
};
$.ajax({
type: "POST",
url: "email-php.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
PHP
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//send email
mail("email#domain.com", "From: " .$email, $message);
}
?>
EDIT: I took the above from various answers on Stack Overflow however couldn't figure out what I am missing or doing wrong. I took most of it from this question here jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined
UPDATE: After #inarilo's suggestion below I have changed everything to the following and now I don't get an email at all. This definitely looks like the better option so I would like to get it to work.
HTML
<section>
<form enctype="multipart/form-data" id="frmemail">
<fieldset class="margin-b">
<legend>Contact Me</legend>
<label for="form_name">Name:<input name="form_name" type="text" value="" required autofocus ></label>
<label for="form_email">Email:<input type="email" name="form_email" value=""></label>
<label for="form_msg">Message:<textarea name="form_msg" rows="5"></textarea></label>
</fieldset>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</section>
JS
$.ajax({
type: "POST",
url: "email-php.php",
data: $("#frmemail").serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
PHP
<?php
if(isset($_POST['name'],$_POST['email'],$_POST['message'])){
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
//send email
mail("landon#thecallfamily.com", "From: " .$email, $message);
}
?>
Final Working Code
HTML
<section>
<form enctype="multipart/form-data" id="frmemail">
<fieldset class="margin-b">
<legend>Contact Me</legend>
<label for="form_name">Name:<input name="form_name" type="text" value="" required autofocus ></label>
<label for="form_email">Email:<input name="form_email" type="email" value=""></label>
<label for="form_msg">Message:<textarea name="form_msg" rows="5"></textarea></label>
</fieldset>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</section>
JS
$(document).ready(function() {
$('#frmemail').submit(function(event) {
$.ajax({
type: 'POST',
url: 'email-php.php',
data: $('#frmemail').serialize(),
success: function() {
$('.success').fadeIn(1000)
}
})
})
})
PHP
<?php
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
$to = "landon#thecallfamily.com";
$subject = "RIA Emails";
$body = "Name: ".$name."\nEmail: ".$email."\nMessage: ".$message;
$headers = "From: " . $email;
//send email
mail($to, $subject, $body, $headers);
?>
You have multiple errors, first of all you are using element ids to pick up the data:
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
but the input elements themselves have no id attribute defined.
Secondly, you are passing name, email and message, but in your PHP you are using name, email and text:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
However, even if correct all this is unnecessarily complicated, you can instead just serialize the form:
In the HTML, add an id to the form:
<form enctype="multipart/form-data" id="frmemail">
In JS, pick up the form and serialize it:
$(document).ready(function(){
$("#frmemail").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "email-php.php",
data: $("#frmemail").serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
});
});
And in PHP simply use the element names, you don't need ids for them:
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
you are trying to get textarea value by using wrong id, it should be:
message: $("#form_msg").val()
not
message: $("#form_email").val()
and in php file, replace the following:
$message = $_POST['text'];
with
$message = $_POST['message'];
that's it :)
try this, (supposed you have put id names on you input form)
JQUERY:
$(document).ready(function(){
$('#submit').on('click',function(){
var name = $('#name').val(),
var name = $('#email').val(),
var name = $('#message').val();
$.ajax({
type: "POST",
url: "email-php.php",
data: {name:name,email:email,message:message},
success: function(data){
alert(data);
}
});
});
});
PHP:
if(isset($_POST['name'],$_POST['email'],$_POST['message'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
echo $name; // then echo $email and then $message
}
I have a html form that is supposed to submit data to a php file through jquery ajax. the code can be seen below.The problem I am having is that on clicking submit, the ajax seems not to be passing data to php as the console.log under the done() function returns a $data object showing that all fields are empty (i.e returning the error messages when the fields are empty). I am simply not getting where the problem is. When I submit the form without using ajax i.e disabling the entire $('form').submit (...) block, the success message returns true. the ajax blocks always returns false
<form id="sds_contact_form" class="sds_form" action="form_submit.php" method="post">
<!-- name -->
<div class="sds_input_group sds_half_field">
<label for="sds_sender_name">full name*</label>
<input id="sds_sender_name" name="sds_customer" type="text" placeholder="eg John smith" required />
<span id="sds_customername_error" class="sds_error_span"></span>
</div>
<!-- email address -->
<div class="sds_input_group sds_half_field">
<label for="sds_sender_email">email*</label>
<input id="sds_sender_email" name="sds_form_email" type="email" placeholder="eg j.smith#example.com" required />
<span id="sds_email_error" class="sds_error_span"></span>
</div>
<!-- subject -->
<div class="sds_input_group">
<label for="sds_email_subject">subject*</label>
<input id="sds_email_subject" name="sds_form_subject" type="text" placeholder="e.g need an app designed" required />
<span id="sds_subject_error" class="sds_error_span"></span>
</div>
<!--enquiry -->
<div class="sds_input_group">
<label for="sds_sender_enquiry">enquiry*</label>
<span id="sds_enquiry_error" class="sds_error_span"></span>
<textarea id="sds_sender_enquiry" name="sds_form_enquiry" placeholder="enter details here" rows="15" required></textarea>
</div>
<!-- submit button -->
<button name="sds_submit_enquiry" type="submit" class="sds_form_button sds_button">send</button>
</form>
This is the jquery code
//form data submission
$('form').submit(function(event){
var form_data = {
'customer_name' : $('#sds_sender_name').val(),
'customer_email' : $('#sds_sender_email').val(),
'email_subject': $('#sds_email_subject').val(),
'enquiry': $('#sds_sender_enquiry').val()
};
console.log(form_data);
$.ajax({
url :'form_submit.php',
type:'POST',
data:form_data,
dataType:'json',
}).done(function(data){
console.log(data);
}).fail(function(xhr, ajaxOptions, thrownError){
console.log("ERROR:" + xhr.responseText+" - "+thrownError);
});
event.preventDefault();
});
This is the PHP Code in form_submit.php
<?php
$data = array();
$errors = array();
//get form data
$customer_name = $_POST['sds_customer'];
$customer_email = $_POST['sds_form_email'];
$email_subject = $_POST['sds_form_subject'];
$enquiry = $_POST['sds_form_enquiry'];
//validate name
if(empty($customer_name)){
$errors['customer_name'] = 'name is required';
}
//validate email
if(empty($customer_email)){
$errors['customer_email'] = 'email is required';
}else{
if(!filter_var($customer_email,FILTER_VALIDATE_EMAIL)){
$errors['customer_email'] = 'email provided is invalid';
}
$customer_email = filter_var($customer_email,FILTER_SANITIZE_EMAIL);
}
//validate form subject
if(empty($email_subject)){
$errors['email_subject'] = 'subject is required';
}else{
$email_subject = filter_var($email_subject,FILTER_SANITIZE_STRING);
}
//validate form comments
if(empty($enquiry)){
$errors['enquiry'] = 'please enter your enquiry';
}else{
$enquiry = filter_var($enquiry,FILTER_SANITIZE_STRING);
}
if(!empty($errors)){
$data['success'] = false;
$data['errors'] = $errors;
}else{
$data['success'] = true;
$data['message'] = "Your email has been sucessfully sent. Thank you for your enquiry. Exepect a response soon!";
//further data processing here....
}
echo json_encode($data);
?>
Your problem is about parameters names At jquery the parameter is defined as:
var form_data = {
'customer_name' : $('#sds_sender_name').val(),
'customer_email' : $('#sds_sender_email').val(),
'email_subject': $('#sds_email_subject').val(),
'enquiry': $('#sds_sender_enquiry').val()
};
At PHP, you are using a sds prefix (as write in the form):
//get form data
$customer_name = $_POST['sds_customer'];
$customer_email = $_POST['sds_form_email'];
$email_subject = $_POST['sds_form_subject'];
$enquiry = $_POST['sds_form_enquiry'];
Your parameters should match with AJAX, not with form (as below).
$customer_name = $_POST['customer_name'];
$customer_email = $_POST['customer_email'];
$email_subject = $_POST['email_subject'];
$enquiry = $_POST['enquiry'];
Or just use serialized on form:
$.ajax(
data: $("#sds_contact_form").serialize(),
/*** others parameters ***/
$("#sds_contact_form").serialize() // returns all the data in your form
$.ajax({
type: "POST",
url: 'form_submit.php',
data: $("#sds_contact_form").serialize(),
dataType:'json',
success: function(data) {
console.log(data);
}
});
In you php file Unserialize your data
unserialize($data);
I'm a fairly new to web development. Mostly I'm a freelance artist trying to make her own web portfolio. Although I recognize the importance of learning the basics of code so I'm trying to do this all myself as I go.
Currently I'm at a stalemate with a simple PHP/HTML Contact Form. I have some forms on my HTML index (it's a one page site) that call in my PHP file to send the message to my email. As you probably would expect it looks a little something like this:
Index.html
<input name="name" type="text" placeholder="First and last name">
<input name="email" type="email" id="email" placeholder="Email address">
<textarea name="message" placeholder="Your Message"></textarea>
<input id="Submit" class="submit_btn" name="submit" type="submit" value="Submit">
</form>
Contactme.php
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: mywebsite.com';
$to = 'twocoffeespoons#gmail.com';
$subject = 'Hello';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
} else {
echo '<p>Something went wrong, go back and stry again!</p>';
}
}
?>
I think I understand the basics, but I'm really not satisfied with my form. When the user hits my submit button the php script is run and they are taken to a different page. I know I could simply change my website to index.php but I'd rather not. Even then the website still refreshes after I hit send. I've been looking through everything I can find, but the tutorials seem really outdated.
Does anybody have some advice? I'd like to use AJAX/JQuery to send the input to my php while the user just gets a "Your Message Has Been Sent Alert" without leaving my website. I'm sorry if my terminology is off or a little confusing. Like I said I'm really new to this, and have been trying to solve this problem for the last three days with no results.
try something like this
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
});
HTML CODE
<form id="ajaxform" action="your_url_goes_here">
.......
</form>
HTML
<input name="name" id="first" type="text" placeholder="First and last name">
<input name="email" type="email" id="email" placeholder="Email address">
<textarea id="message" name="message" placeholder="Your Message"></textarea>
<input id="Submit" class="submit_btn" name="submit" type="submit" value="Submit">
<span class="error" style="display:none">All Fields Are Required!</span>
<span class="success" style="display:none">Contact Form Submitted Successfully</span>
Script
$(function() {
$(".submit_btn").click(function() {
var name = $("#first").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email+ '&message' + message;
if (name == '' || email == '' || message == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else {
$.ajax({
type: "POST",
url: "Contactme.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
$("#formid").submit(function() {
// your code
return false; //return false also works..
});
- just try this code it will help you , submit your form as method="POST" and action="abc.php";
<?php
if(isset($_POST['submit'])){
$to=$_POST['email'];
$from=$_POST['name'];
$message=$_POST['message'];
$headers = "From:" . $from;
mail($to,$message,$headers);
echo "Mail Sent.";
}
?>
I have a simple html form where I will send a mail and there is another file named as ajax-form-submit.php where the file process will do. Now I want to show the success or failure message in the html file through ajax.
So my html form with jQuery goes like this
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value ="Ravi"/> <br/>
Last Name: <input type="text" name="lname" value ="Shanker" /> <br/>
Email : <input type="text" name="email" value="xx#xxx.com"/> <br/>
<input type="button" id="simple-post" value="Run Code" name="submit"/>
</form>
<div id="simple-msg"></div>
<script>
jQuery(document).ready(function() {
jQuery("#simple-post").click(function() {
jQuery("#ajaxform").submit(function(e) {
jQuery("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax( {
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR) {
jQuery("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault(); //STOP default action
});
$("#ajaxform").submit(); //SUBMIT FORM
});
});
</script>
Now the php file where the mail will go will be like this
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$ToEmail = 'test#demo.com';
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br>";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>";
$mail = mail($ToEmail, $MESSAGE_BODY);
if($mail) {
echo "Mail sent successfully";
}
else {
echo "oops there is some error";
}
}
?>
I want the success message or the error message should be shown in html page.
Its showing only any message is written outside the if (isset($_POST['submit'])) { function but by doing this I can't show the success message or error message. So can someone kindly tell me how to do this? Any help will be really appreciable. Thanks.
HTML
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" id="fname" value ="Ravi"/> <br/>
Last Name: <input type="text" name="lname" id="lname" value ="Shanker" /> <br/>
Email : <input type="text" name="email" id="email" value="xx#xxx.com"/> <br/>
<input type="button" id="simple-post" value="Run Code" name="submit"/>
</form>
<div id="simple-msg"></div>
<script type="text/javascript">
jQuery("#simple-post").click(function() {
jQuery("#simple-msg").html("<img src='loading.gif'/>");
var formURL = $(this).attr("action");
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
$.ajax({
url : formURL,
type: "POST",
data : {
aFname: fname,
aLname: lname,
aEmail: email,
aSubmit:"submit"
},
success:function(data, textStatus, jqXHR) {
jQuery("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown){
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
});
</script>
PHP
if (isset($_POST['aSubmit'])) {
$name = $_POST['aFname'];
$lname = $_POST['aLname'];
$email = $_POST['aEmail'];
$ToEmail = 'test#demo.com';
$MESSAGE_BODY = "Name: ".$_POST["aFname"].' '.$_POST["aLname"]."<br/>";
$MESSAGE_BODY .= "Email: ".$_POST["aEmail"]."<br/>";
$mail = mail($ToEmail, $MESSAGE_BODY);
if($mail) {
echo "Mail sent successfully";
}
else{
echo "oops there is some error";
}
}
Note:_I would like to mention here that i have not shown any efforts to prevent SQL injection or any other kind of vulnerability-prevention here just because that can increase the complexity for you. But, make sure that before posting such code to live sites, you incorporate all efforts to prevent your site._
I would suggest to send the status (success or error) back to the client using JSON (using PHP json_encode()). For that, you will also need to add a JSON listener in your page using JQuery script.
var text = $("input#text").val();
if (text == "") {
$("input#text").focus();
alert("Please complete all fields");
return false;
}
I have this jquery above to validate a textarea called "text". This, along with other values, get .ajax sent to a php page for sending an email. The email comes through fine with everything else in ok, but the textarea comes through as "undefined"? Any ideas? Do i need to post some more code?
EDIT:
Rest of the code:
the php:
$email = $_REQUEST['email'] ;
$text = $_REQUEST['text'] ;
$name = $_REQUEST['name'] ;
$detail = "Name: ".$name."\nMessage: ".$text;
mail( "xxxxxxxxx", "Subject: Contact Form",
$detail, "From: $email" );
echo "Thank you for getting in touch";
complete jquery:
$(function() {
$('#submit').live('click',function(){
var name = $("input#name").val();
if (name == "") {
$("input#name").focus();
alert("Please complete all fields");
return false;
}
var email = $("input#email").val();
if (email == "") {
$("input#email").focus();
alert("Please complete all fields");
return false;
}
var text = $("input#text").val();
if (text == "") {
$("input#text").focus();
alert("Please complete all fields");
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&text=' + text;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailform.php",
data: dataString,
success: function() {
alert("Thanks, we will be in touch soon");
}
});
return false;
});
});
The html:
<form method='post' action='mailform.php' class="form">
<p class="name">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</p>
<p class="email">
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
</p>
<p class="text">
<label for="text">Nature of Enquiry</label>
<textarea id="text" name="text"></textarea>
</p>
<p class="submit">
<input type="submit" id="submit" value="Send" />
</p>
</form>
I had a similar problem and my problem was with the php code. Try yo have a look there see if the #textarea gets _POST - ed correctly.
I am using this and works perfectly for me:
//we need to get our variables first
$email_to = 'xxxxx#yahoo.com'; //the address to which the email will be sent
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message']. "\n\n";
/*the $header variable is for the additional headers in the mail function,
we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
That way when we want to reply the email gmail(or yahoo or hotmail...) will know
who are we replying to. */
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
}else{
echo 'failed';// ... or this one to tell it that it wasn't sent
}
Not sure what's going on, like the other user said I believe to be a problem with the way the data is being carried over to the php script.
Try to look into $.post and serialize() functions that jquery can offer:
to give you an idea:
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
--- Due some checks to see if the info is correct---
if(error == false){
//#contact_form has all the variables that get serialized and sent to the php
and you can get a message back to check if everything went okay.
$.post("your_php_code.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#cf_submit_p').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});