I wrote this script which doesn't send the data from the AJAX to the PHP file. I debugged it with logging the data that's in the form before it ran through the AJAX function. It gave me this data:
Form: name=jim&email=info%40test.com
However, I get an empty alert and I receive an empty e-mail.
HTML
<form name="form" id="form" class="form" method="post">
<input type="text" class="text border" name="name" id="name" placeholder="Name" />
<input type="text" class="text" name="email" id="email" placeholder="E-mail" />
<input type="submit" class="button" value="Submit" />
</form>
JS
jQuery(function(){
jQuery('#form').submit(function(event){
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "includes/post.php",
data: jQuery('#form').serialize(),
success: function(data){
jQuery("#form").addClass("inactive");
jQuery("#message").addClass("active");
alert(data);
}
});
});
});
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = mysql_real_escape_string($_POST["name"]);
$email = mysql_real_escape_string($_POST["email"]);
$to = "test#hidden.com";
$message = '
<html>
<body>
<p>
<strong>Name: </strong> '.$name.' <br/>
<strong>E-mail: </strong> '.$email.' <br/>
</p>
</body>
</html>
';
$subject = 'New entry: '.$name.', '.$email;
$headers .= "From: ".$name." ".$$email."\r\n";
$headers .= "X-Mailer: PHP's mail() Function\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
mail($to, $subject, $message, $headers);
}
?>
Try the below code,
Update your PHP with the below,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);
echo $name;// this will see in your response
$to = "test#gmail.com";
$message = '
<html>
<body>
<p>
<strong>Name: </strong> ' . $name . ' <br/>
<strong>E-mail: </strong> ' . $email . ' <br/>
</p>
</body>
</html>
';
$subject = 'New entry: ' . $name . ', ' . $email;
$headers = "From: " . $name . " " . $email . "\r\n";
$headers.= "X-Mailer: PHP's mail() Function\n";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
mail($to, $subject, $message, $headers);
}
Nothing is being returned from your php, and you need some form of server side validation, here is a complete code you can use:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'your#yourdomain.com'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
// Check name
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
You should write echo statement after mail() function. The string written in echo statement will display in alert.
for example : echo "Mail sent successfully";
Related
Hi i have been trying for a good 2 hours to get this dropdown menu to get the selected result to go to email through post method im new to php and i think i could just do with abit of guidance ill post html php js code below.i have tried many ways this isnt my only edit ive literally tried everything i just need a little help
html
<div class="col-lg-3">
<div class="form-group mt-2">
<div class="dropdown" >
<select name="vehicles" id="vehicles" class="ddstyle">
<option value="motor" selected>Motorcycle</option>
<option value="Car">Car</option>
<option value="Small">Small Van</option>
<option value="Opel">Opel</option>
<option value="Midi">Midi Van</option>
<option value="SWB">SWB up to 2.4m</option>
<option value="MWB3">MWB up to 3m</option>
<option value="LWB4">LWB up to 4m</option>
<option value="XLWB4">XLWB 4m+</option>
<option value="Luton">Luton</option>
<option value="T5">7.5T</option>
</select>
</div>
</div>
</div>
PHP
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$dod = $_POST['dod'];
$yourname = $_POST['yourname'];
$tel = $_POST['tel'];
$caddy = $_POST['caddy'];
$cpost = $_POST['cpost'];
$daddy = $_POST['daddy'];
$dpost = $_POST['dpost'];
$dofd = $_POST['dofd'];
$Car = $_POST['Car'];
$Small = $_POST['Small'];
$Opel = $_POST['Opel'];
$Midi = $_POST['Midi'];
$MWB = $_POST['MWB'];
$MWB3 = $_POST['MWB3'];
$LWB4 = $_POST['LWB4'];
$XLWB4 = $_POST['XLWB4'];
$Luton = $_POST['Luton'];
$T5 = $_POST['T5'];
//*$vehicles = $_POST['$vehicles'];**/
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
if(isset($_POST['vehicles']) && $_POST['vehicles']=='motor') echo $value;
if(trim($name) == '') {
echo '<div class="error_msg">You must enter your company name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_msg">Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_msg">You have entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($dod) == '') {
echo '<div class="error_msg">Please enter your collection date.</div>';
exit();
}
if(trim($dofd) == '') {
echo '<div class="error_msg">Please enter your drop off deadline.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "example#example.net";
$address = "admin#ready2gologistics.co.uk";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = ' ' . $name . ' has a possible job!';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "$name wants a quote details are listed below." . PHP_EOL . PHP_EOL;
$e_content =
"
Company: $name
Name of Person: $yourname
Contacts email: $email
Contacts Telephone Number: $tel
Desired Collection Date: $dod
Drop Off Deadline: $dofd
Collection Address: $caddy
Collection Post Code: $cpost
Destination Address: $daddy
Destination Post Code: $dpost
Addtional Information: $comments
test: $value
" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_msg'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your quote has been submitted to us. To see how we use your information check out our <a href='PrivacyPolicy.html".$link_address."'>Privacy Policy</a></p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
JavaScript
//Contact
$('#working_form').submit(function() {
var action = $(this).attr('action');
$("#message").slideUp(750, function() {
$('#message').hide();
$('#submit')
.before('<img src="" class="gif_loader" />')
.attr('disabled', 'disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val(),
dod: $('#dod').val(),
dofd: $('#dofd').val(),
yourname: $('#yourname').val(),
cpost: $('#cpost').val(),
caddy: $('#caddy').val(),
tel: $('#tel').val(),
daddy: $('#daddy').val(),
dpost: $('#dpost').val(),
vehicles: $('#vehicles').val(),
value: $('#value').val(),
},
function(data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.gif_loader').fadeOut('slow', function() {
$(this).remove()
});
$('#submit').removeAttr('disabled');
if (data.match('success') != null) $('#cform').slideUp('slow');
}
);
});
return false;
});
In $.post request pass send value
$.post(action, {
...other data
value: $('#value').val(),
send: $('#send').val(),
}
Because your $value vehicle data is depended on if(isset($_POST['send'])) check
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
I want to redirect the user to another page only after displaying a success message. The code below redirects to the another page even if the page is refreshed without submitting any data.
Code Snippet
<?php
// We will store our status message later
$message = '';
// Let's check form submitted
if( isset( $_POST['action'] ) && $_POST['action'] == 'submit' ) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['number'];
$message_text = $_POST['address'];
if (isset($_POST['action']))
{
// Validate required fields
if( $name == '' || $email == '' || $message_text == '' ){
$message = "<p class=\"error\">Please fill out all required fields.</p>";
}
// send email after validation
else {
// Email will be sent at this email
$mailto = 'nepstarditsolutions#gmail.com';
// Let's create html email format
// (You can use html in this email format)
// Email headers
$headers = "From: " . strip_tags( $email ) . "\r\n";
$headers .= "Reply-To: ". strip_tags( $email ) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Email body
$message = "<html><body>";
$message .= "<h3>Contact Info: </h3>";
$message .= "<p><strong>Name: </strong> ". strip_tags( $name ) . "</p>\r\n";
$message .= "<p><strong>Email: </strong> ". strip_tags( $email ) . "</p>\r\n";
$message .= "<p><strong>Contact Number: </strong> ". strip_tags( $phone ) . "</p>\r\n";
$message .= "<p><strong>Alternate Email: </strong> ". strip_tags( $_POST['altemail'] ) . "</p>\r\n";
$message .= "<p><strong>Hosting Package: </strong> ". strip_tags( $_POST['cradio'] ) . "</p>\r\n";
$message .= "<p><strong>Address: </strong>". strip_tags( $message_text ) . "</p>\r\n";
$message .= "</body></html>";
// Email subject
$subject = "Contact Info from ".$name;
// Send email
$mail_status = #mail( $mailto, $subject, $message, $headers );
if( $mail_status ){
$message = '<div class="alert alert-success">Quotation submitted Successfully ! </div>';
}
else {
$message = '<div class="alert alert-danger">Error in sending the Quotation ! </div>';
}
}
}
}
?>
I need help in 2 things
Success message should be displayed for 2 seconds (before the redirect).
How to redirect using JS in php?
Standard "vanilla" JavaScript way to redirect a page
You can use the code below to redirect the user after form submission code.
if( $mail_status ){
echo "
<script>
setTimeout(function() {
window.location = 'http://www.example.com/newlocation';
}, 2000);
</script>
";
}
MDN web docs on how setTimeout works
Hope it helps!
I am working on a form located in the notify button here
I am testing the form now and I get every submission in my email, but on the frontend my success message is showing on the screen.
I would like for this form to work exactly like the contact form on the site where the success message pops up in a placeholder.. or at the bottom of the form
the html and js for the form are below. I have a feeling like I messed up on the class and/or id somewhere. I got all of this code online and have been editing it to make it do what I need it to do LOL! now I am stuck
HTML
<form action="php/newsletter-process.php" id="newsletter-form" method="post">
<input type="text" class="form-control form-control-custom" tabindex="-1"
id="text-field-nl" name="text-field-nl">
<!-- Input Name -->
<div class="nl-form-group" id="name-field">
<label for="form-name" class="sr-only">Name</label>
<input type="text" class="form-control form-control-light"
id="form-name" name="form-name" placeholder="Name">
</div>
<!-- /End Input Name -->
<!-- Input Email -->
<div class="nl-form-group" id="email-field">
<label for="form-email" class="sr-only">Email</label>
<input type="email" class="form-control form-control-light"
id="form-email" name="form-email" placeholder="Email">
</div>
<!-- /End Input Email -->
<!--Check Interest-->
<div class="nl-form-group">
<p>Which are you more interested in?</p>
<input type="checkbox" id="workbook" name="interest-type[]" value="Digital Workbook"/> Digital Workbook<br/>
<input type="checkbox" id="vclass" name="interest-type[]" value="Virtual Class Session"/>Virtual Class Session
</div>
<!-- /End Input Group -->
<!-- Submit Button -->
<div class="btn-row">
<div class="form-group">
<button type="submit" class="btn btn-light" role="button">
Send Message
</button>
</div>
</div>
<!-- /End Submit Button -->
<!-- Message Alert -->
<!--div id="message-newsletter" class="message-wrapper text-white message">
<span><i class="icon icon-sm icon-arrows-slim-right-dashed"></i><label
class="message-text" for="email"></label></span>
</div-->
<div id="message-newsletter" class="message-wrapper text-white message">
<i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
<span class="message-text"></span>
</div>
<!-- /End Message Alert -->
</form>
<!-- /End Newsletter Form -->
JS
/*
--------------------------------
Ajax Contact Form
--------------------------------
+ https://github.com/pinceladasdaweb/Ajax-Contact-Form
+ A Simple Ajax Contact Form developed in PHP with HTML5 Form validation.
+ Has a fallback in jQuery for browsers that do not support HTML5 form validation.
+ version 1.0.1
+ Copyright 2014 Pedro Rogerio
+ Licensed under the MIT license
+ https://github.com/pinceladasdaweb/Ajax-Contact-Form
*/
(function ($, window, document, undefined) {
'use strict';
var form = $('#newsletter-form'),
messageContainer = $('#message-newsletter'),
messageText = $('#message-newsletter .message-text');
form.submit(function (e) {
// remove the error class
form.find('.nl-form-group').removeClass('error');
messageContainer.removeClass('error');
var errorAll = '';
// get the form data
var formData = {
'name': $('input[name="form-name"]').val(),
'email': $('input[name="form-email"]').val(),
'textfield': $('input[name="text-field"]').val()
};
// process the form
$.ajax({
type: 'POST',
url: 'php/newsletter-process.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
// handle errors
if (!data.success) {
if (data.errors.name) {
$('#name-field').addClass('error');
errorAll = data.errors.name;
}
if (data.errors.email) {
$('#email-field').addClass('error');
errorAll = errorAll + ' ' + data.errors.email;
}
messageContainer.addClass('error');
messageText.html(errorAll);
} else {
// display success message
messageText.html(data.confirmation);
$('#newsletter-form .form-control').each(function () {
$(this).fadeIn().val($(this).attr('placeholder'));
});
}
});
messageContainer.slideDown('slow', 'swing');
setTimeout(function () {
messageContainer.slideUp('slow', 'swing');
}, 10000);
}).fail(function (data) {
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
PHP
<?php
$subjectPrefix = 'App It Out Notify';
$emailTo = 'taking this out';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = stripslashes(trim($_POST['form-name']));
$email = stripslashes(trim($_POST['form-email']));
$spam = $_POST['textfield'];
foreach($_POST['interest-type'] as $inttype) {
$check_boxes .= $inttype." ";
}
if (empty($name)) {
$errors['form-name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['form-email'] = 'Email is invalid.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Email: </strong>'.$check_boxes.'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
Change your button type to "button" to not reload the page.
<button type="button" class="btn btn-light" role="button">
Send Message
</button>
Use the Ajax 'success' and 'error' properties to handle the request success/errors
$.ajax({
type: 'POST',
url: '...',
data: {...},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
Use the success/error function to push your success message into the HTML
<div id="message-newsletter" class="message-wrapper text-white message">
<i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
<span class="message-text" id="messageText"></span>
</div>
JS
document.getElementById('messageText').innerHTML = <success or error message>
Your code is a little bit messed up, what you can do is:
Step one
Serialize your form data, change your formData variable to:
var formData = $("form#newsletter-form").serialize();
also change the sent data and the url in your ajax:
$.ajax({
type: 'POST',
url: 'index.php' /*Now, we are requesting the index page instead of the php page.*/,
data: {'submission': formData},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
Step two
Instead of writing a messed up php code you can create a functions like this:
<?php
class classname{
public function funcName($formdata,$errors,$data){
$get = explode('&', $formdata); // explode with and
foreach ( $get as $key => $value) {
$valn[ substr( $value, 0 , strpos( $value, '=' ) ) ] = substr( $value, strpos( $value, '=' ) + 1 ) ;
}
// access your query param
$name = stripslashes(trim($valn['name']));
$email = stripslashes(trim($valn['email']));
$spam = $valn['spam'];
foreach($_POST['interest-type'] as $inttype) {
$check_boxes .= $inttype." ";
}
if (empty($name)) {
$errors['form-name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['form-email'] = 'Email is invalid.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Email: </strong>'.$check_boxes.'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
}
?>
Now, we need to request the function from the index.php. so, add this php code to your index page
<?php
if (isset($_POST['submission'])) {
header('Content-Type: application/json; charset=utf-8');
$subjectPrefix = 'App It Out Notify';//I don't know if you need this in your php file if so you can add it.
$emailTo = 'taking this out';//I don't know if you need this in your php file if so you can add it.
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
require_once('yourphppage.php');
$conform = new classname;
$search->funcName($_POST['data'],$errors,$data);
die();
}
?>
I have been struggling to send uploaded file to email using php. My problem is whatever i give the email uploaded file send to that email. Here is my code it is not working.
<?php
if (isset($_POST['submit'])) {
$headers = "From: abc#example.com mailer \r\n";
echo $message .= $_POST['message'];
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
if (file_exists($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$to_user = "bnarendra6036#gmail.com";
$flgchk = mail("$to_user", "$subject", "$message", "$headers");
if ($flgchk) {
echo "Done, <br>";
}
else
{
echo "Failed to send email, <br>";
echo "Redirecting you to your Inbox";
}
}
?>
<form name="form1" method="post" action="" enctype="multipart/form-data">
<table>
<tr>
<td width='20'><b>Select File:</b> </td>
<td width='20'><input type="file" name="attachment"></td>
</tr>
<p><td>
<input type="submit" name="Submit" value="Send" class="Submit" /></td></tr></table>
</p>
</form>
So can you please adjust this code or send me any another working code.
I have created demo using PHPMailer. First load phpmailer.class.php file.
You can download from here : http://github.com/PHPMailer/PHPMailer
require_once('/class.phpmailer.php'); // Your full path of phpmailer.php file
$email = new PHPMailer();
$email->From = 'From email address'; //From email address
$email->FromName = 'Your name'; //your name
$email->Subject = 'Message'; //Message
$email->Body = 'Body Text Message'; //Body message
$email->AddAddress( 'To email address' ); //To email address
$attach_file = 'Your file path'; //Attached file path
$email->AddAttachment( $attach_file, 'file_name.doc' );
return $email->Send();
On a Linux server, I have an ajax form that gets posted to a js script, which in turn posts to a php routine for sending a web site email contact form (Styleshout-Puremedia template). I know the post is occurring to js, and to the php page. I get an httpd server error on the php page that "$Error is undefined". However if I define it as NULL or '' it exists and therefore doesn't pass the test "if (!$Error)". If I create a hard-coded php script using the mail function, the e-mail works so php and sendmail are all configured properly. Can someone help as to why this php script doesn't work, or how to fix the "$Error" error?
PHP code:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'info#mydomain.com';
if($_POST) {
$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check First Name
if (strlen($fname) < 2) {
$error['fname'] = "Please enter your first name.";
}
// Check Last Name
if (strlen($lname) < 2) {
$error['lname'] = "Please enter your last name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Name
$name = $fname . " " . $lname;
// Set Message
$message = "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['fname'])) ? $error['fname'] . "<br /> \n" : null;
$response .= (isset($error['lname'])) ? $error['lname'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Thanks for your help!!
-Rob
You can always just initialize $error as
$error = [];
and then check for errors by
if(count($errors) === 0){
//no errors
}
Or, just use if(!isset($error)){//no errors}