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.";
}
?>
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 have a contact form on my website that is not posting the success or error message as it should.
The weird thing is I have used this exact same form, php, and ajax script on several other sites and it works great. In fact, it used to work great on the site in question.
The website is https://www.pouncingfoxdesign.com. The contact form is at the bottom. Feel free to fill it out for testing purposes.
Here's the form and script:
<div class="col-md-8 col-sm-9 wow form1 fadeInLeft">
<div class="contact-form clearfix contactForm">
<form id="form" action="php/email.php" class="contactForm"
method="post">
<div class="messages"></div>
<div class="input-field">
<input type="text" class="form-control" name="name"
placeholder="Your Name" required="">
</div>
<div class="input-field">
<input type="email" class="form-control"
name="email" placeholder="Your Email" required="">
</div>
<div class="input-field message">
<textarea name="message" class="form-control"
placeholder="Your Message" required=""></textarea>
</div>
<input type="submit" name="submit" class="btn btn-blue
pull-right" value="SEND MESSAGE" id="msg-submit">
<div class="g-recaptcha fadeInLeft" data-
sitekey=""></div>
</form>
</div> <!-- end .contact-form -->
</div> <!-- .col-md-8 -->
<script> $('#form').on('submit', function(e) {
event.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize(); //Serialized the form data for
process.php
// $('#loader', '#form').html('<img src="img/forms/loading.gif" />
Please Wait...');
$.ajax({
type: 'POST',
url: 'php/email.php', // Your form script
data: post_data,
success: function(msg) {
var old_html = form.html()
$(form)
.html(msg).fadeIn();
setTimeout(function(){
$(form)
.html(old_html).fadeIn();
}, 4000);
},
error: function(xhr, ajaxOptions, err){
var old_html = form.html()
$(form).fadeOut(500)
.html("<h3>There was an error. Please try again.
</h3>").fadeIn();
setTimeout(function(){
$(form).fadeOut(500)
.html(old_html).fadeIn();
}, 3000);
}
});
});
</script>
And here's the PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h1>Submission successful</h1>
<h3>Thank you for contacting us!</h3>
</div>
</div>";
$to = "email#email.com";
$subject = "$name\n filled Pouncing Fox Desing Form";
$txt = "From: $name\n E-Mail: $email\n Comments:\n $message";
$headers = "From: Pouncing Fox Design" . "\r\n" ;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents
("https://www.google.com/recaptcha/api/siteverify?
secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if (mail($to, $subject, $txt, $headers)) {
echo "$success"
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
What I want it to do is replace the form with the success message for a few seconds and then go back to the form. What it does instead is just go to the email.php file with the success message being all that's on the screen.
If you want to check out https://www.mooreengaging.com, the same script and php file is used for that site. It works great and you can see my intended results. Again, feel free to fill out the form for testing purposes.
I have tried to use other ajax scripts and have tried to rework it several different times, but no matter what when clicking submit it just loads the php file. It's like it is bypassing the ajax script altogether.
Thanks!
EDIT:
I have received the emails from you guys testing and they look right. So it is working, just not posting the success message as I'd like.
Ok, I figured it out. I added <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> to the top of the page under the header.
I thought it was best to put jquery at the bottom?
Did it fail because I was trying to run that script before it loaded jquery?
Change
$('#form').on('submit', function(e)
To
$('#form').on('submit', function(event)
Because you use
event.preventDefault();
I have a forum and its one part of the page and it works fine but when clicking on the send button the url always changes to my .php file so : (mysite.com/forum.php)
is there away to stop this? and have it send the infomation to the email and thats it without changing the url? I would like to keep the page the forum is in a .html because the forum just one of many things on the page.
Here are my forum and php code so far: (Its basic)
<form method="post" action="forum.php">
<div class="field name-box">
<input type="text" name="name" id="name" placeholder="Who Are You?"/>
<label for="name">Name</label>
<span class="ss-icon">✔</span>
</div>
<div class="field email-box">
<input type="text" name="email" id="email" placeholder="name#email.com"/>
<label for="email">Email</label>
<span class="ss-icon">✔</span>
</div>
<div class="field msg-box">
<textarea id="message" name="message" rows="4" placeholder="Your message goes here..."/></textarea>
<label for="msg">Msg</label>
<span class="ss-icon">✔</span>
</div>
<input id="submit" class="button" name="submit" type="submit" value="submit" />
</form>
The php:
<?php
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$from = 'From: Datcroft Website';
$to = 'MyEmail#hotmail.co.uk';
$subject = 'Datcroft Site Message';
$body = "From: $name\n E-Mail: $email\n Message: $message\n";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
} else {
}
}
?>
Any pointers or help? I am a really noob in Php and also Ajax (Im guessing Ajax will be a solution to come up in the answers)
Thank you in advanced!
Could this work as is? from fbo3264 below in answers.
var Name = $("#Name").text();
var Email = $("#Email").text();
var Message = $("#Message").text();
$(document).ready(function() {
$('#Forum1').submit(function(ev) {
ev.preventDefault();
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
type : 'POST', //we use POST to submit the form
url : forum.php, // the url where we want to POST
data:{
Name:Name,
Email:Email,
Message:Message
},
success:function(response)
{
//handle success (show a success modal or someting)
},
error: function(jqXHR, textStatus, errorThrown)
{
//handle error
}
});
});
});
I'd use jQuery and ajax as you've guessed:
$(document).ready(function () {
// manually submit the form
$('#Forum1').submit(function (ev) {
ev.preventDefault();
var params = {"email": $("#Email").val(), "name": $("#Name").val(),
"message": $("#Message").val(), "submit": true};
$.ajax({
type: 'POST', //we use POST to submit the form
url: 'forum.php', // the url where we want to POST
data: params,
success: function (response)
{
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown)
{
//handle error
}
});
});
});
If you are sending a request to forum.php, the URL is going to change. You can use Apache mod_rewrite to change the URL to match the pattern you want. Some rule like this one, could do the job:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.html
I have this for document ready using jquery 1.11 from cdn and jquery migrate 1.2.1 from cdn. The ajax is to send form values to a file "mail.php" that sits in the same directory and simply checks if it was called via ajax then grabs the post variables and send them via email. It can't be a cross domain issue. Also, the alerts below confirm that it is grabbing the input values OK. This works fine for ie10+ and all other browsers.
However, for ie8+9 - the email is sent to me blank..in other words the post variables aren't being recieved?
$("#contactform").submit( function (e) {
e.returnValue=false;
e.preventDefault();
alert('form submitted');
if (checkValidation()) {
//if valid, send ajax
var name=$('#form-name').val();
var email=$('#form-email').val();
var contact_number=$('#form-contact-number').val();
var message=$('#form-message').val();
alert(name+email+contact_number+message);
$.ajax({
type: 'POST',
url: 'mail.php',
//data: JSON.stringify(parameters),
contentType: "json",
// data: $(this).serialize(),
data:{'name':name,'email':email,'contact_number':contact_number,'message':message},
dataType: "text",
cache: false,
success: function(data) {
// do something with ajax data
$('.form-response').css({color:'black',backgroundColor:'white',textAlign:'center'}).text('Thank you, we will contact you shortly.').show();
$('input').val('').trigger('blur');
$('textarea').val('').trigger('blur');
setTimeout(function(){
$('.form-response').hide();
scroll_to_top();
},3000);
},
error:function (xhr, ajaxOptions, thrownError){
console.log('error...', xhr);
//error logging
},
complete: function(){
//afer ajax call is completed
}
});
} else {
alert('Please re-enter your input and try again.');
$('input').val('');
$('textarea').val('');
$("input").trigger("blur");
$("textarea").trigger("blur");
$('#form-name').focus();
}
});
My form on index.html looks like:
<form class="form-style validate-form clearfix" id="contactform" action="mail.php" method="POST" role="form">
<div class="col-md-6"><div class="form-group"><input type="text" class="text-field form-control validate-field required" data-validation-type="string" id="form-name" placeholder="Full Name" name="name"></div>
<div class="form-group"><input type="email" class="text-field form-control validate-field required" data-validation-type="email" id="form-email" placeholder="Email Address" name="email"></div>
<div class="form-group"><input type="tel" class="text-field form-control validate-field phone" data-validation-type="phone" id="form-contact-number" placeholder="Contact Number" name="contact_number">
<input type="text" id="address-input" name="address" style="display: none!important;"></div></div><div class="col-md-6">
<div class="form-group"><textarea placeholder="Message..." id="form-message" class="form-control validate-field required" name="message"></textarea></div>
<div class="form-group"><button type="submit" id="submitBtn" class="btn btn-sm btn-outline-inverse">Submit</button></div></div>
</form>
my mail.php:
<?php
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
# is ajax
if (empty($_POST["address"])) {
$from = $_POST["name"]; // sender
$subject = 'From: ' . $from;
$email = $_POST["email"];
$tel = $_POST["contact_number"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
$textToSend = 'From: ' . $from . "\n";
$textToSend .= 'Email: ' . $email . "\n";
$textToSend .= "Phone: " . $tel . "\n";
$textToSend .= 'Message: ' . $message . "\n";
// send mail
mail("contact#domain.net", $subject, $textToSend, "From: $from\n");
echo "Thank you, we will contact you shortly.";
echo '
<script>
$("input").val("");
$("textarea").val("");
setTimeout(function(){
scroll_to_top();
},3000);
</script>
';
} else {
echo 'Thank you, we will contact you shortly.';
echo '
<script>
$("input").val("");
$("textarea").val("");
setTimeout(function(){
scroll_to_top();
},3000);
</script>
';
}
}else{
header( 'Location: http://www.myhomepage.net' ) ;
die();
}
Edit:: incase a question about it gets brought up.. I use the address field in the form to act as my "honeypot" method .. which basically means if the field address ( which is set to display none ) is filled it..then the submission was most likely a bot and will be discarded.
Probably it's that your variables are double-quoted see heere for more info https://stackoverflow.com/a/7081920/3501422
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.