I'm sending form data to a PHP script via AJAX/JSON.
Put this together using online tutorials but it seems to be working fine.
I want to try to edit the PHP script to sanitize the received, serialized AJAX/JSON data before the data is inserted into email.
I've checked around on StackOverflow and more generally on the web but can't find a definitive answer that fits the scripts I'm working with.
The code I'm using is summarized below.
jQuery (abbreviated code)
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
...
}
PHP (abbreviated code)
Data received via AJAX is placed into array:
$fields = array('client_name' => 'Name', 'client_phone' => 'Phone', 'client_email' => 'Email',
'client_message' => 'Message');
Data is then placed into $emailText variable using foreach loop:
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n\n";
}
}
Data sent in email:
mail($sendTo, $subject, $emailText, $headers);
I'm wondering if there any way the serialized data can be extracted and sanitized in PHP before the email is sent?
Say, with something like:
$sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
Any advice much appreciated.
Spent a few hours messing around with this and finally cracked it. Not sure if it is all perfectly written code - but hey, it works.
Probably a routine exercise for someone experienced with jQuery validation and AJAX but quite a mountain to climb for me.
I used the jbvalidator plugin in at:
jbvalidator plugin
... as well as Bootstrap 5.
Here's the finished, working code:
HTML
<form method="post" class="needs-validation" novalidate>
<div class="mb-3">
<input type="text" name="name" class="form-control" placeholder="Your Name" required>
</div>
<div class="mb-3">
<input type="tel" name="phone" class="form-control" placeholder="Your Phone" required>
</div>
<div class="mb-3">
<input type="email" name="email" class="form-control" placeholder="Your Email" required>
</div>
<div class="mb-3">
<textarea rows="4" cols="20" name="message" class="form-control" placeholder="Your Message" required></textarea>
</div>
<input type="submit" name="send" value="Send"><br>
<div class="output_message"></div>
</form>
jQUERY
<script>
$(function (){
let validator = $('form.needs-validation').jbvalidator({
errorMessage: true,
successClass: true,
language:
"https://emretulek.github.io/jbvalidator/dist/lang/en.json"
});
validator.reload();
$(document).on('submit', '.needs-validation', function(){
$.ajax({
method:"post",
url:"process-form.php",
data: $(this).serialize(),
success: function (data){
var alertBox = '<div class="alert alert-success
alert-dismissable fade show" role="alert">Message sent. Thank you.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-
label="Close"></button></div>';
$('.output_message').html(alertBox);
$('.needs-validation').trigger("reset");
$('.needs-validation input, .needs-validation
textarea').removeClass("is-valid");
if(data.status === 'error') {
var errorBox = '<div class="alert alert-danger
alert-dismissable fade show" role="alert">An error occurred. Please try again
later. <button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button></div>';
$('.output_message').html(errorBox);
$('.needs-validation').trigger("reset");
$('.needs-validation input, .needs-validation
textarea').removeClass("is-valid");
}
}
})
return false;
});
})
</script>
PHP
Code can surely be improved but, like I said, for the moment it's working.
<?php
if (isset($_REQUEST['name'], $_REQUEST['email'])) {
$name = $_REQUEST['name'];
$phone = $_REQUEST['phone'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$sanitizedName = filter_var($name, FILTER_SANITIZE_STRING);
$sanitizedPhone = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
$sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
$sanitizedMessage = filter_var($message, FILTER_SANITIZE_STRING);
$email_message = "Name: " . $sanitizedName . "\n\n"
. "Phone: " . $sanitizedPhone . "\n\n"
. "Email: " . $sanitizedEmail . "\n\n"
. "Message:\n\n" . $sanitizedMessage;
$to = 'email#someplace.com';
$subject = 'New message';
$headers = 'From: admin#somedomain.com' . "\r\n" .
'Reply-To: ' . $sanitizedEmail . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_email = mail($to, $subject, $email_message, $headers);
echo ($send_email) ? 'success' : 'error';
}
?>
Cheers!
Related
Project structure is as follows
C:\xampp\htdocs\myProject\Documentation
C:\xampp\htdocs\myProject\HTML\css
C:\xampp\htdocs\myProject\HTML\images
C:\xampp\htdocs\myProject\HTML\js
C:\xampp\htdocs\myProject\HTML\videos
C:\xampp\htdocs\myProject\HTML\404.html
C:\xampp\htdocs\myProject\HTML\contact.php
C:\xampp\htdocs\myProject\HTML\index.html
C:\xampp\htdocs\myProject\PSD
I have a contact form in index.html that is controlled by a javascript file. This code stops default form submit, performs error checks and then uses ajax to make a post request to contact.php. The javascript code runs, it detects the php (see the alert in the code below just after the axjax funtion call. The value of d is the php script in the alert, but none of the debug lines in the php code get called and it never returns 'success'.
Here is the form
<form class="form-horizontal" id="phpcontactform">
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Full Name" name="name" id="name">
</div>
<div class="control-group">
<input class="input-block-level" type="email" placeholder="Email ID" name="email" id="email">
</div>
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Mobile Number" name="mobile" id="mobile">
</div>
<div class="control-group">
<textarea class="input-block-level" rows="10" name="message" placeholder="Your Message" id="message"></textarea>
</div>
<div class="control-group">
<p>
<input class="btn btn-danger btn-large" type="submit" value="Send Message">
</p>
<span class="loading"></span> </div>
</form>
here is the javascript
// JavaScript Document
$(document).ready(function() {
$("#phpcontactform").submit(function(e) {
e.preventDefault();
var name = $("#name");
var email = $("#email");
var mobile = $("#mobile");
var msg = $("#message");
var flag = false;
if (name.val() == "") {
name.closest(".control-group").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".control-group").removeClass("error").addClass("success");
} if (email.val() == "") {
email.closest(".control-group").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".control-group").removeClass("error").addClass("success");
} if (msg.val() == "") {
msg.closest(".control-group").addClass("error");
msg.focus();
flag = false;
return false;
} else {
msg.closest(".control-group").removeClass("error").addClass("success");
flag = true;
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&mobile=" + mobile.val() + "&msg=" + msg.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "http://localhost/myProject/HTML/contact.php",
cache: false,
success: function (d) {
alert("d: "+d);
$(".control-group").removeClass("success");
if(d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="green">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="red">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").click(function () {
$(".control-group").removeClass("success").removeClass("error");
});
})
And finally here is the php
<?php
echo "<script>console.log('Debug Objects:' );</script>";
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$msg = $_REQUEST["msg"];
echo "<script>";
echo "alert('this also works');";
echo "</script>";
$to = "myemail#gmail.com";
if (isset($email) && isset($name) && isset($msg)) {
$subject = $name."sent you a message via Raaga";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: ".$name."<br/> Email: ".$email ."<br/> Mobile: ".$mobile." <br/>Message: ".$msg;
echo "<script>alert('this maybe works');</script>";
$mail = mail($to, $subject, $msg, $headers);
if($mail)
{
echo 'success';
}
else
{
echo "<script>alert('name:'+$name);</script>";
echo 'failed';
}
}
echo "<script>alert('this finally works');</script>";
?>
I tried moving contact.php to the htdocs root but that didnt work. Have turned off all antivirus and firewalls but that didnt work either. Am at a loss. Thought php was supposed to work out of the box with xampp?
Okay so thanks to ADyson for the help. The issue was not that php isn't running, its that the mail server was not properly configured.
I am trying to send an email to user account using php mail() function.The mail is sent successfully but the issue is that it is sending me blank emails with no values in them! The code for the contact page that sends the email is as follows:-
<form class="contact-form" method="POST" action="sendemail.php">
<div class="row-fluid">
<div class="span5">
<label>First Name</label>
<input type="text" class="input-block-level" required="required" placeholder="Your First Name" name="name">
<label>Last Name</label>
<input type="text" class="input-block-level" required="required" placeholder="Your Last Name" name="lname">
<label>Email Address</label>
<input type="text" class="input-block-level" required="required" placeholder="Your email address" name="email">
</div>
<div class="span7">
<label>Message</label>
<textarea name="message" id="message" required="required" class="input-block-level" rows="8" name="message"></textarea>
</div>
</div>
<input type="submit" class="btn btn-primary btn-large pull-right" value="Send Message" />
<p> </p>
</form>
and sendemail.php page code is as follows:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = "An enquiry sir";
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';
echo $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
Why is the output I get blank in my email id, for example:
Name:
Email:
Subject:
Message:
P.N: I am using here a nova template theme.
The form is being submitted via AJAX using the following JavaScript:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
the form submission code is not submitting the form data. Here is the code you provided:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
and this is what it should be:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
Remove the echo from the line that defines $body
From this...
echo $body = 'Name: ' . $name . "\n\n" . 'Email
To this...
$body = 'Name: ' . $name . "\n\n" . 'Email
Please help me with decoding what the real issue is. The issue is that I keep getting a blank email, despite all my tweaking and research on this code. Below are my html, javascript (ajax) and php code.
HTML code: file named contact.html
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
AJAX code:file named main.js
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
PHP code: file named sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
with this I keep on getting a blank email as depicted below
Name:
Email: Blank
Phone: Blank
Subject: Blank
Message: Blank
Have you tried with-out the die() at the end of your script? I think you might be killing your page too fast.
Also try creating a catch like this :
if (!mail(...))
{
// Reschedule for later try or panic appropriately!
}
Furthermore, you are suppressing warnings with # before mail();
Try removing the #.
Edit : Also, try removing the trims.
You have not set data while calling ajax, may be this is your problem.
When I test your code then I see that there fires a GET-request although you define the mehtod as POST in the form attribute. (Maybe that´s why jQuery use GET as default...). So the $_POST['name'] is empty because the parameter is in $_GET['name'].
And I can´t see the request parameters when I´m submiting the form. (Maybe that´s why the 'data' property is not set..)
Please try to complete the $.ajax with these:
method: 'POST'
data: $(this).serialize()
A BIG THANKS to ALL of you guys(#Mateusz Klimentowicz,#Mat VP,#Jose Manuel Abarca Rodríguez ,# Vladimir Nu). I actually followed your instructions and ended up correcting both the JS file and the PHP file as shown below:
JS file:
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
While the PHP code became this below:
<?php
$status = array(
'type'=>'success',
'message'=>'Thank you for contacting us. As soon as possible we will contact you!'
);
$fail = array(
'type'=>'fail',
'message'=>'Please try again. Your mail could not be delivered!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#mail.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
header('Content-type: application/json');
if($success){
echo json_encode($status);
}
else{
echo json_encode($fail);
}
?>
And after using this code as stated below, i end up not getting any blank page email. Email is now delievered with it's content. Thanks a bunch.
Email is arriving at the destination address but with blank fields. What is the cause?
My use of mail() is as follows:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'info#siteaddress.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
And the form HTML is:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input type="text" class="form-control" required placeholder="Name" name="name" id="name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="text" class="form-control" required placeholder="Email address" name="email" id="email">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Message" name="message" id="message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger btn-lg">Send Message</button>
</div>
</div>
</div>
</form>
$subject = #trim(stripslashes($_POST['subject'])); but your form don't have subject, you should add it.
Don't suppress errors by #, because you never will know what exactly happens with your code.
Finally Got the Answer.... Problem is that my form was not posting anything because the following script was missing
<script>
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'),$(this).serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
</script>
i have added $(this).serialize() to the script and now the mail is working properly...
Thanks all of you....
Hi I´m have the same problem on a 000webhost app. I solve this with two moodifications
1rst:
Add var name = $("input#name").val(); for a form values and in to the ajax function name: name, for a form values
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: {
name: name,
email: email,
subject: subject,
message: message,
},
cache: false,
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email enviandose</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success"> Gracias por la consulta, a la brevedad estaremos respondiendo</p>').delay(3000).fadeOut();
//clear all fields
$('#main-contact-form').trigger("reset");
});
});
2nd: The tag id"name" id"email" id"XX" in mi Form in my case
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
//to Replace This
$header .= 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>',,$header);
if( $success == true )
{
//success Message
}
else{
//Error Message
}
Very new to this so apologies is my question is basic but it's stumped me for some hours.
I have a contact form which uses a bit of AJAX to POST to my PHP file. The problem im having is that when i try to get the PHP to email that data to myself, it isn't reading the POST values. The PHP was working when i tested it without the JS/AJAX post method, but in order to stop the page refresh I have gone with the AJAX option. Now that i've added the ajax in, the email result isn't showing up with the data (I can inspect and see that the Form Data is filled, just unclear why it isnt populating in the email) :
Name:
Email:
Message:
Any guidance as to why my mail server only receives the text but not the POST
Opening & Closing HTML on form:
<form data-parsley-validate action="./assets/contactform.php" method="POST">
<div class="formRow">
<label for="name" class="obscure">Name</label>
<input type="text" name="nameInput" id="name" placeholder="Name" required data-parsley-error-message="Please enter your name"></input>
</div>
<div class="formRow">
<label for="email" class="obscure">Email</label>
<input name="emailInput" id="email" type="email" placeholder="Email" required data-parsley-error-message="Please enter a valid email address"></input>
</div>
<div class="formRow">
<label for="message" class="obscure">Message</label>
<textarea name="messageInput" id="message">Message</textarea>
</div>
<input type="submit" name="submit"></input>
PHP Script:
<?php
$to = 'hello#kymlangford.com';
$subject = 'Post from your website';
$message = "Name: " . $_POST['nameInput'] . "\n Email: " . $_POST['emailInput'] . "\n Message: " . $_POST['messageInput'];
$headers = 'From: hello#kymlangford.com' . "\r\n" .
'Reply-To: ' . $_POST['emailInput'] . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
exit;
?>
Java for the form:
$(function() {
$.ajax({
type: 'POST',
url: './assets/contactform.php',
data: { name : $('input[name=nameInput]').val(),
email : $('input[name=emailInput]').val(),
message : $('textarea[name=messageInput]').val()
},
dataType: 'json'
})
event.preventDefault();
});
});
--Update 08/07/2014--
Below is the jquery code that solved my problem
// get the data from the form
$('form').submit(function(event){
var fdata = $(this).serializeArray();
fdata.push({ name: 'submit', value: true });
$.post('./assets/contactform.php', fdata, function (data) {
alert('Data Loaded:' + data); });
console.log(fdata);
event.preventDefault();
});
});
I think you can use jquery which is the same like ajax.
Here is the HTML code
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("sendemail.php", $("#contactform").serialize(), function(response)
{
$('#message').html(response);
});
return false;
});
});
</script>
</head>
<body>
<p>
<form action="" method="post" id="contactform" >
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="emailcontent">Email Content:</label><br />
<textarea name="emailcontent" id="emailcontent"></textarea><br />
<input type="button" value="Send Email" id="submit" /><div id="message"> </div>
</form>
</p>
</body>
</html>
Here is the PHP code, save it with 'sendemail.php' filename
$name = $_POST['name'];
$email = $_POST['email'];
$emailcontent = $_POST['emailcontent'];
$to = 'youremail#domain.com';
$subject = 'the subject';
$emailcontent = 'FROM: '.$name.' Email: '.$email.'Content: '.$emailcontent;
$headers = 'From: youremail#domain.com' . "\r\n";
mail($to, $subject, $message, $headers);
echo "Your email was sent!";