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
}
Related
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.
I've created a simple AJAX, Jquery, PHP contact form on my website with inputs: Name, Email and Message. The problem is that when you write an actual email into the email field the message never comes to my inbox. It works only when the Email input field contains 1 word with no # sign.
My HTML:
<p class="form">Name</p>
<input type="text" name="userName" id="userName">
<p class="form">Email</p>
<input id="userEmail" type="email" name="userEmail">
<p class="form">Message</p>
<textarea id="msg" name="msg"></textarea><button onClick="sendContact();"></button>
My JavaScript:
function sendContact() {
jQuery.ajax({
url: "contact_me.php",
data:'userName='+$("#userName").val()+'&userEmail='+
$("#userEmail").val()+'&msg='+
$("#msg").val(),
type: "POST",
success:function(){
sendSuccess();
},
error:function (){}
});
};
My PHP:
<?php
$to = "dusset#gmail.com";
$from = $_POST['userEmail'];
$name = $_POST['userName'];
$subject = $name . "has sent you a message from .design";
$message = $name . " wrote the following:" . "\n\n" . $_POST['msg'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);?>
Any idea what could be the problem, please?
Try changing how you pass the data to Ajax. An example:
function sendContact() {
jQuery.ajax({
url: "contact_me.php",
data: { userName: $("#userName").val(), userEmail: $("#userEmail").val(), msg: $("#msg").val()},
type: "POST",
success:function(){
sendSuccess();
},
error:function (){}
});
};
I have tried everything to get this form to work but no luck.
I guess abide is working now but my php is not sending the email. I don't even think that my php is getting called anyway.
my code is below
form code
line 434
<form id="myForm" data-abide action="mail.php" method="post">
<div class="contactform">
<div class="item item-pair">
<label for="name">Full Name
<input type="text" name="name" id="name" class="small-input cat_textbox" required pattern="[a-zA-Z]+" maxlength="255">
<small class="error small-input">Name is required and must be a string.</small>
</label>
<label for="email">Email Address
<input type="text" name="email" id="email" class="small-input cat_textbox" maxlength="255" required >
<small class="error small-input">An email address is required.</small>
</label>
</div>
<div class="item">
<label>Comments</label>
<textarea cols="10" name="message" id="message" rows="4" class="cat_listbox" required ></textarea>
<small class="error">Please enter your comments</small>
</div>
<div class="item">
<input class="button alert small" type="submit" value="Submit" id="catwebformbutton">
</div>
</div>
</form>
javascript code
line 627
<script>
$('#myForm').submit(function(e) {
//prevent default form submitting.
e.preventDefault();
$(this).on('valid', function() {
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for reponse
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"mail.php",
data: dataString,
success: function(data){
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<h2>Thanks!</h2>")
.append("<p>Dear "+ name +", I will get back to you as soon as I can ;)</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
});
</script>
html link
http://tayrani.com
Please help
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["message"];
$msg = "
Name:$name
Email:$email
Comment:
$comments";
$to = "tayrani#hotmail.com";
$subject = "website email";
$message = $msg;
$headers = "form";
mail($to,$subject,$message,$headers);
?>
Thanks for the help I got it working. It turned out to be Hotmail that is not accepting emails for some reason. So, I replaced the Hotmail account with a Gmail account and it worked. I also updated my code with the following
html code for the form
<form id="myForm" data-abide="ajax" action="mail.php" method="post">
<div class="contactform">
<div class="item item-pair">
<label for="name">Full Name
<input type="text" name="name" id="name" class="small-input cat_textbox" required pattern="[a-zA-Z]+" maxlength="255">
<small class="error small-input">Name is required and must be a string.</small>
</label>
<label for="email">Email Address
<input type="email" name="email" id="email" class="small-input cat_textbox" maxlength="255" required >
<small class="error small-input">An email address is required.</small>
</label>
</div>
<div class="item">
<label>Comments</label>
<textarea cols="10" name="message" id="message" rows="4" class="cat_listbox" required ></textarea>
<small class="error">Please enter your comments</small>
</div>
<div class="item">
<input class="button alert small" type="submit" value="Submit" id="catwebformbutton" name="btnSubmit">
</div>
</div>
</form>
My javascript code including fixing the submitting twice issue
<script>
$('#myForm').submit(function(e) {
//prevent default form submitting so it can run the ajax code first
e.preventDefault();
$(this).on('valid', function() { //if the form is valid then grab the values of these IDs (name, email, message)
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for reponse (store the values here)
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"mail.php", //runs the php code
data: dataString, //stores the data to be passed
success: function(data){ // if success then generate the div and append the the following
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<br /><h4>Thanks!</h4>")
.append('<p><span style="font-size:1.5em;">Hey</span> <span class="fancy">'+ name +'</span>,<br />I´ll get back to you as soon as I can ;)</p>')
.hide()
.fadeIn(1500);
},
error: function(jqXHR, status, error){ //this is to check if there is any error
alert("status: " + status + " message: " + error);
}
}); //End Ajax call
//return false;
});
});
</script>
<script>
$(document).foundation('abide', 'events'); // this was originally before the above code, but that makes the javascript code runs twice before submitting. Moved after and that fixes it.
</script>
Here is the php code
<?php
if(isset($_POST["name"])){
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["message"];
$msg = "
Name: $name
Email: $email
Comments:
$comments";
$to = "h2hussein#gmail.com";
$subject = "Tayrani.com Contact Form";
$headers = "From: <$email>";
mail($to,$subject,$msg,$headers);
}else{
}
?>
I struggled for 3 days to get this done but thanks to my colleague/friend Adam as he really helped me with it.
I hope this is useful for other people.
Thanks,
Hussein
tayrani.com
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.