Submit form in React.js using Ajax - php

Creating my first application in React.js and want to submit contact form to a email with Ajax. I've used this solution as guideline: https://liusashmily.wordpress.com/author/liusashmily/ but the full component file is not available, only parts and I cant reach the author.
Contact component
// Create Component
class Contact extends React.Component {
constructor(props){
super(props);
this.state = {
contactEmail: '',
contactMessage: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleChangeMsg = this.handleChangeMsg.bind(this);
}
handleChange(event) {
this.setState({
contactEmail: event.target.value,
});
}
handleChangeMsg(event) {
this.setState({
contactMessage: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
this.setState({
type: 'info',
message: 'Sending…'
});
$.ajax({
url: 'php/mailer.php',
type: 'POST',
data: {
'form_email': this.state.contactEmail,
'form_msg': this.state.contactMessage
},
cache: false,
success: function(data) {
// Success..
this.setState({
type: 'success',
message: 'We have received your message and will get in touch shortly. Thanks!'
});
}.bind(this),
error: function(xhr, status, err) {
this.setState({
type: 'danger',
message: 'Sorry, there has been an error. Please try again later or visit us at SZB 438.'
});
}.bind(this)
});
}
render() {
return (
<div className="contact">
<form className="form" onSubmit={this.handleSubmit} id="formContact">
<label>Email</label>
<input id="formEmail" type="email" name="formEmail" value={this.state.contactEmail} onChange={this.handleChange} required />
<label>Meddelande</label>
<textarea id="formMsg" name="formMsg" rows="8" cols="40" value={this.state.contactMessage} onChange={this.handleChangeMsg} required></textarea>
<input type="submit" value="Submit" className="btn--cta" id="btn-submit" />
</form>
</div>
)
}
}
My PHP file mailer.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// $name = strip_tags(trim($_POST[“form_name”]));
// $name = str_replace(array(“\r”,”\n”),array(” “,” “),$name);
$email = filter_var(trim($_POST["formEmail"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["formMsg"]);
// Check that data was sent to the mailer.
if ( empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "mimilundberg#icloud.com";
// Set the email subject.
$subject = "New message from $email Via React Site";
// Build the email content.
$email_content .= "Email: $email\n\n";
$email_content .= "Message: \n$message\n";
// Build the email headers.
$email_headers = "From: <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn’t send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Getting following error in console log:
POST http://localhost:8080/php/mailer.php 404 (Not Found)
..and it says that error is in the "jquery-3.2.1.min.js:4" file.
I'm including jQuery script in html doc:
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<!-- <link rel="stylesheet" href="dist/styles.css"> -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div id="app"></div>
<script src="dist/bundle.js"></script>
</body>
</html>
So incredibly grateful for any input!

I found the solution. Here is my Contact component:
import React, { Component } from 'react';
// Contact component render contact form
class Contact extends React.Component {
constructor(props){
super(props);
this.state = {
contactEmail: '',
contactMessage: ''
};
this._handleSubmit = this._handleSubmit.bind(this);
this._handleChange = this._handleChange.bind(this);
this._handleChangeMsg = this._handleChangeMsg.bind(this);
}
// Change state of input field so text is updated while typing
_handleChange(e) {
this.setState({
contactEmail: e.target.value,
});
}
// Change state of input field so text is updated while typing
_handleChangeMsg(e) {
this.setState({
contactMessage: e.target.value
});
}
_handleSubmit(e) {
e.preventDefault();
this.setState({
contactEmail: '',
contactMessage: ''
});
$.ajax({
url: process.env.NODE_ENV !== "production" ? '/getMail' : "http://www.fransbernhard.se/magden/php/mailer.php",
type: 'POST',
data: {
'form_email': this.state.contactEmail,
'form_msg': this.state.contactMessage
},
cache: false,
success: function(data) {
// Success..
this.setState({
contactEmail: 'success',
contactMessage: '<h1>Kontakt skickad!</h1><p>Återkommer så fort som möjligt.</p>'
});
$('#formContact').slideUp();
$('#formContact').after(this.state.contactMessage);
console.log('success', data);
}.bind(this),
// Fail..
error: function(xhr, status, err) {
console.log(xhr, status);
console.log(err);
this.setState({
contactEmail: 'danger',
contactMessage: '<h1>Sorry det blev fel</h1><p>Försök gärna igen, eller mejla mig direkt på magdamargaretha#gmail.com</p>'
});
console.log(this.state.contactEmail + this.state.contactMessage + 'fail');
}.bind(this)
});
}
render() {
return (
<div className="contact" id="contact">
<div className="filter">
<form className="form" onSubmit={this._handleSubmit} id="formContact">
<label>Email</label>
<input id="formEmail" type="email" name="formEmail" value={this.state.contactEmail} onChange={this._handleChange} required/>
<label>Meddelande</label>
<textarea id="formMsg" name="formMsg" rows="8" cols="40" value={this.state.contactMessage} onChange={this._handleChangeMsg} required></textarea>
<input type="submit" value="Submit" className="btn--cta" id="btn-submit" />
</form>
</div>
</div>
)
}
}
export default Contact;
mailer.php file:
<?php
// trim() function strips any white space from beginning and end of the string
$email = filter_var(trim($_POST["form_email"]), FILTER_SANITIZE_EMAIL);
// strip_tags() function strips all HTML and PHP tags from a variable.
$message = strip_tags($_POST["form_msg"]);
// Check that data was sent to the mailer.
if ( empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "mimilundberg#icloud.com";
// Set the email subject.
$subject = "Message to magdalundberg.se from: $email";
// Build the email content.
$body .= "Email: $email\n\n";
$body .= "Message: \n$message\n";
// success
$success = mail($recipient, $subject, $body, "From:" . $email);
// Send the email.
if ($success) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn’t send your message.";
}
?>

As React is UI component framework you can use third party library for ajax post.
https://www.npmjs.com/package/react-axios
Here is an example of how to use this.
https://handyopinion.com/reactjs-post-form-with-ajax/

Related

How to integrate reCAPTCHA into existing php contact form?

I am trying to integrate a reCAPTCHA with my existing php contact form. Please can someone help? I have added the relevant code into the html form, I just don't know how to adapt my mailer.php code to perform the necessary backend checks and process the form data. I'm new to php and the code i have used I adapted from a site on the web. The form also uses ajax and query form validation.
<form id="form-ajax" class="form-ajax" method="post" action="mailer.php">
<input id="name" class="form-name" type="text" name="name" placeholder="Name" required>
<span class="error"></span>
<input id="email" class="form-email" type="email" name="email" placeholder="Email Address" required>
<span class="error"></span>
<textarea id="message" class="form-message" name="message" placeholder="Message..." required></textarea>
<span class="error"></span>
<div class="g-recaptcha" data-sitekey="my-site-key"></div>
<button class="form-submit" type="submit" name="submit">Send</button>
</form>
<script>
$(function() {
// Get the form
var form = $('#form-ajax');
// Get the messages div
var formMessages = $('#form-messages');
// Set up an event listener for the contact form
$(form).submit(function(event) {
// Stop the browser from submitting the form
event.preventDefault();
// Serialize the form data
var formData = $(form).serialize();
// Submit the form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text
$(formMessages).text(response);
// Clear the form
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
</script>
<?php
// Only process POST requests
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address
$recipient = "email#example.com";
// Set the email subject
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank you! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

Can't explain 400 bad request error from php/ajax form

I always get an unexplained 400 error when submitting an email through my form and i cannot understand why this is.
This worked on my local server, but when i uploaded it on the live website
Here is my HTML
<form method="post" id="ajax-contact" class="clearfix" action="js/mailer.php">
<input class="sb-search-input" placeholder="I want your freebies!" type="email" id="email" name="name" >
<input class="sb-search-submit" type="submit">
<button class="formbutton" type="submit">
<span class="fa fa-check"></span>
</button>
</form>
Here is my AJAX
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#email').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
Here is my PHP
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
echo "$email";
// Check that data was sent to the mailer.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "ahamdan#kindredbay.co.uk, aemmadi#kindredbay.co.uk";
// Set the email subject.
$subject = "New enquiry from $email";
// Build the email content.
$email_content .= "Email: $email\n\n";
// Build the email headers.
$email_headers = "From: $email <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Try replacing this in your form:
<input class="sb-search-input" placeholder="I want your freebies!" type="email" id="email" name="email" >

Sending email with PHP on a modal with AJAX

I have a modal that contains a form that sends email using PHP. I do not want that Modal to close when the email is sent so I have tried to use AJAX to send it without refreshing the page. However, I cannot keep it from closing when I push submit and cannot figure out what the problem is. The emails still send so I believe it has something to do with AJAX.
<?php include 'email_form.php';?>
<?php echo $result; ?>
<form method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Your Name"
value="<?php echo $_SESSION['post-data']['name']; ?>" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Your Email"
value="<?php echo $_SESSION['post-data']['email']; ?>" />
</div>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" id="comment" name="comment"><?php echo $_SESSION['post-data']['comment']; ?></textarea>
</div>
<div class="modal-footer text-center">
<input type="submit" name="submit" id="submit" class="btn" value="Submit"/>
</div>
</form>
The PHP
<?php
$_SESSION['post-data'] = $_POST;
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$comment = strip_tags($_POST['comment']);
if ($_POST["submit"]) {
if (!$_POST['name']) {
$error="<br />Please enter your name";
}
if (!$_POST['email']) {
$error.="<br />Please enter your email address";
}
if (!$_POST['comment']) {
$error.="<br />Please enter a comment";
}
if ($_POST['email']!="" AND !filter_var($_POST['email'],
FILTER_VALIDATE_EMAIL)) {
$error.="<br />Please enter a valid email address";
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s)
in your form:</strong>'.$error.'</div>';
} else {
if (mail("user#email.com", "Comment from website.com", "Name: ".
$_POST['name']."
Email: ".$_POST['email']."
Comment: ".$_POST['comment']))
{
$result='<div class="alert alert-success"><strong>Thank
you!</strong> I\'ll be in touch.</div>';
unset($_SESSION['post-data']['name']);
unset($_SESSION['post-data']['email']);
unset($_SESSION['post-data']['comment']);
session_destroy();
} else {
$result='<div class="alert alert-danger">Sorry, there was
an error sending your message. Please try again later.</div>';
}
}
}
?>
JavaScript
<script>
$(document).ready(function () {
$('#submit').click(function(event) {
$('.modal').on('hide.bs.modal', function(e) {
e.preventDefault();
});
var formData = {
'name' : $('input[id=name]').val(),
'email' : $('input[id=email]').val(),
'comment' : $('input[id=comment]').val(),
};
$.ajax({
type: "post",
url: "email_form.php",
data: formData,
success: function(msg){
alert("Email sent");
},
error: function(){
alert("Please try to resubmit");
}
});
});
});
</script>
I have also tried this but it too closed the modal
<script>
$(document).ready(function () {
$('#submit').submit(function(event) {
event.preventDefault();
var formData = {
'name' : $('input[id=name]').val(),
'email' : $('input[id=email]').val(),
'comment' : $('input[id=comment]').val(),
};
$.ajax({
type: "post",
url: "email_form.php",
data: formData,
success: function(msg){
alert("Email sent");
},
error: function(){
alert("Please try to resubmit");
}
});
});
});
</script>
Instead of calling
e.preventDefault();
in the first version of your javascript just do the following:
return false;
You can also use the second version of your html and instead of calling event.preventDefault(); , return false at the end of the function after the ajax call.
Your second Javascript example is closer to the right answer.
You're attaching the submit event to the button id rather than the form ID, which is incorrect. You're also querying your input attributes needlessly. Modify your markup with something like this:
<form id="email-submit-form" method="post">
Then modify your Javascript with something like this:
<script>
$(document).ready(function () {
$('#email-submit-form').submit(function(event) {
event.preventDefault();
var formData = {
'name' : $('#name').val(),
'email' : $('#email').val(),
'comment' : $('#comment').val(),
'submit' : 'AJAX' //Rudimentary example to help you differentiate between POST types
};
$.ajax({
type: "post",
url: "email_form.php",
data: formData,
success: function(msg){
alert(msg); //See my notes below
},
error: function(){
alert("Please try to resubmit");
}
});
});
});
You also have a lot wrong with your PHP, as it would never fire due to the absence of a "submit" field from your original AJAX POST request. Additionally, you're trying to set fields as session data, never using them in the script, and then you're unsetting them on success.
Session data is intended to persist data between requests. You aren't doing that here.
Secondly, even if you output an error message (which your AJAX method won't see, because you're not outputting anything), the status code returned by the request will be 200 and the success message will fire every time, even with malformed data.
This should be closer to what you want:
<?php
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$comment = strip_tags($_POST['comment']);
if ($_POST["submit"]) {
$error = '';
if (!$name){
$error="<br />Please enter your name";
}
if (!$email) {
$error.="<br />Please enter your email address";
}
if(!$comment) {
$error.="<br />Please enter a comment";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error.="<br />Please enter a valid email address";
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s) in your form:</strong>'.$error.'</div>';
}
else {
if(mail("user#email.com", "Comment from website.com",
"Name: ".$name."
Email: ".$email."
Comment: ".$comment)
){
$result='<div class="alert alert-success"><strong>Thank you!</strong> I\'ll be in touch.</div>';
} else {
$result='<div class="alert alert-danger">Sorry, there was
an error sending your message. Please try again later.</div>';
}
}
/*
This will only fire on your above AJAX request, and stop the server from running
after this point. All you need is the response for your AJAX script to read
*/
if($_POST['submit'] === 'AJAX'){
die($result);
}
}
?>
With all of that said, this is largely untested and isn't guaranteed to work perfectly. Instead, this should give you a little bit of a better idea in terms of how everything works together.
Good luck.

How to send confirmation email via PHP and Ajax?

I am working on a project with a simple PHP form with Ajax. The form sends email successfully but in AJAX messages it displays an error message that I have set: 'Oops! An error occured and your message could not be sent.
' could it be a server problem?
Also I want to send user a thank you (form submit confirmation) email after they submit the form on my website.
HTML Code:
<form id="ajax-contact" method="post" action="mailer.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Name" required name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="email" name="email" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="3" id="message" name="message"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
PHP mailer.php Code:
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "receiveremail#somewhere.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
AJAX Code:
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
just change this line and check once. even i had the same issue, i solved like this,
data: formData
to
data: {"postvalues":formData},
or
data: formData to data: {name: "sample",email:"your emal",message:"hi how are you"}
If you are using first one, make necessary changes in mailer.php. Like this
$post = $_POST['postvalues'];
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
If you follow second method, you cant serialize() form, and no need to change anything in mailer.php.
To send email to user who filled the form, use this
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
mail($email, "Contact Us", "Thank you for contacting us, we will get back to you soon", $email_headers)
}

show ajax success or error message when form is submitted in the same page

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.

Categories