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.
Related
I'm trying to config a contact form based on php/ajax to a website, but I can't manage to add a "success" message after the form is submitted. I receive the email correctly if I keep the "action" parameter to the php file inside form tag, but the page gets redirected to the blank php page. However, if I remove the link, the email is not sent.
I've tried in the past hours many of the suggestions I found online, but I can't manage to make it work properly. Any guesses?
Thanks
HTML
<form id="contact-form" method="POST" action="simple-email-form-v1/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
</div>
PHP
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "abcde#gmail.com";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Your website
";
$referer = $_SERVER['HTTP_REFERER'];
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "includes/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = `enter code here`"From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
?>
JS
$(document).ready(function () {
$("#contact-form").validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true,
maxlength: 8000
}
},
messages: { // custom messages
fullname: {
required: "Por favor, insira seu nome"
},
email: {
required: "Por favor, insira seu email"
},
message: {
required: "Por favor, insira sua mensagem",
maxlength: jQuery.format("The maxlength for message is {0} !")
},
},
submitHandler: function(form) {
$form = $(form);
$container = $form.parent();
w = $form.outerWidth();
h = $form.outerHeight();
$form.hide();
$('#msg_submitting', $container).width(w).height(h).fadeIn(1000);
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
success: function (data) {
$("#mail-status").html(data);
},
error:function (){}
});
return false;
}
});
});
Where is the "mail-status" id in html? You can replace "mail-status" with "errors".
The issue is there is no "mail-status" id in a page, so it is not displaying response on that div.
Define "mail-status" on html or just replace "mail-status" with "errors", as your html contains .
Put the <div id="errors"></div> outside the form element. When you are hiding the form the <div id="errors"></div> also gets hidden hence you cannot see anything.
<form id="contact-form" method="POST" action="header.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id="errors"></div>
Also in the php file you need to echo $message; so that it should be available in the ajax data param.
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
echo $message;
Perhaps this might help you:
<div id="mail-status"></div>
<form id="contact-form" method="POST" action="simple-email-form-v1/form-to-email.php">
First, add this element to the html :
<div id="mail-status"></div>
Then add preventDefault() to the js to prevent the form from submitting :
<script>
$(document).ready(function () {
$("#contact-form").submit(function(e) {
e.preventDefault(); // added preventDefault()
}).validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true,
maxlength: 8000
}
},
messages: { // custom messages
fullname: {
required: "Por favor, insira seu nome"
},
email: {
required: "Por favor, insira seu email"
},
message: {
required: "Por favor, insira sua mensagem",
maxlength: jQuery.format("The maxlength for message is {0} !")
},
},
submitHandler: function (form) {
$form = $(form);
$container = $form.parent();
w = $form.outerWidth();
h = $form.outerHeight();
$('#msg_submitting', $container).width(w).height(h).fadeIn(1000);
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
success: function (data) {
$("#mail-status").html(data);
},
error: function () {}
});
$form.hide(); // moved below ajax call
return false;
}
});
});
</script>
Then don't forget to add echo statement to the php :
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
echo $message;
Perhaps the way you handle the submit is causing the page to redirect?
Change your button type submit to a button. See below,
<input type="button" name="submit" value="Submit" id="submit" />
Then, target the button click for the form submission, like this,
$(document).ready(function () {
$('#submit').click(function(){
//do you logic here
});
});
When changing the button type to be a button, you don't need to worry about preventDefault() for submission, because submission only happens through through Ajax / JS.
Hope this helps.
Cheers
sorry that I start this topic. I know that there were a lot of topics in this matter. But still I can not deal with it, because I need the success / failure messages to be displayed as below:
<!-- Form in modal -->
<?PHP if(isset($_SESSION['error_msg'])){echo $_SESSION['error_msg']; unset($_SESSION['error_msg']);}?>
<?PHP if(isset($_SESSION['success_msg'])){echo $_SESSION['success_msg']; unset($_SESSION['success_msg']);}?>
<form id="test-form action="test.php" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="submit" name="save-test-form" value="Save">
</form>
/* test.php */
<?PHP
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$_SESSION['success_msg'] = 'All is well.';
}else{
$_SESSION['error_msg'] = 'Enter the email.';
}
}else{
$_SESSION['error_msg'] = 'Enter the name.';
}
}
?>
And jquery?
My point is to submit this form without reloading the page (because it's in the modal window) and I have to display success / failure messages in the form (also without reloading the page). I do not know how to do it.
I will be grateful for the help and explanation of how to do it step by step.
Your PHP script is executed on page reload, so when using Ajax you must manually show messages from server:
// PHP
$response = [];
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$response['success'] = 'All is well.';
}else{
$response['error_msg'] = 'Enter the email.';
}
}else{
$response['error_msg'] = 'Enter the name.';
}
echo json_encode($response); // Format array as json and output it
die(); // No other output, just JSON
}
// jQuery
$.ajax({
url: '',
method: 'POST',
dataType: 'json',
data: {},
success: function (response) {
if (typeof response.success !== 'undefined') {
$('#responseMessage').text(response.success);
} else {
$('#responseMessage').text(response.error_msg);
}
}
})
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.
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/
I'm using CodeIgniter for my web app and I'm currently stuck with AJAX forms.
I've made an view for my "forget password" modal and it looks like this:
<form action="<?=base_url()?>users/forgot_pass" method="post" id="forget_pass_form">
<div class="form_header">
<h1>Forgot your password?</h1>
</div>
<?php if($ajax_error == 0) { ?>
<div class="front_success">
<p>Password was succesfully sent to your email address.</p>
</div>
<?php } ?>
<?php if($ajax_error == 1) { ?>
<div class="login_error">
<p>Email address was not found in the database.</p>
</div>
<?php } ?>
<div id="loading_spinner"></div>
<p><input type="text" name="to_email" placeholder="Sähköpostiosoite" class="user" style="background-postion: -200px; margin-top: 20px;" />
<input type="submit" name="to_submit" value="Lähetä salasana" class="login_submit" id="forget-pass" /></p>
</form>
And here's my controller for it:
<?php
class Users extends CI_Controller {
public function forgot_pass()
{
if(isset($_POST['to_submit'])) {
$this->load->model('user');
$email = $_POST['to_email'];
$email_addr = $this->user->get_email_address($email);
if($email_addr) {
foreach($email_addr as $row) {
$this->load->library('email');
$this->email->from('me');
$this->email->to($email);
$this->email->subject('Testing');
$this->email->message('Your password is: ' . $row['password']);
if(!$this->email->send()) {
$data['ajax_error'] = 1;
} else {
$data['ajax_error'] = 0; }
}
}
}
$this->load->view('header');
$this->load->view('index', $data);
$this->load->view('footer');
}
}
?>
I won't post my Model since I know 100% sure it works and it only contains that one method to check if email is found in the database.
Now I want to make it more dynamic by using AJAX. I want it to echo the success message inside a div if the email address was found in the database and the mail was sent
to that email address, otherwise I want it to echo out the error "User was not found in the database".
Here's my js file which for now:
$(document).ready(function() {
$("form#forget_pass_form").on('submit', function(){
var from = $(this);
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
}
});
return false;
});
});
The AJAX part itself is working, but I just don't know how to implement those messages. Any help would be much appreciated.
make your html code like this
<div class="front_success" style="display:none">
<p>Password was succesfully sent to your email address.</p>
</div>
<div class="login_error" style="display:none">
<p>Email address was not found in the database.</p>
</div>
small change in controller:-
if($this->email->send()) {
echo '1';
} else {
echo '0';
}
so what ever your controller return based on that success function will make the dive show
try to make you ajax code like this :-
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
},
success: function (data) {
//alert(data); alert it if you want to check the function output
if(data == '1'){
//if the email is send then it return 1 so that you show success msg
$("#login_success").show();
}else{
//if the email is not send then it return 0 so that you show error msg
$("#front_error").show();
}
$("#loading_spinner").hide();// hide when ajax complete
}
});