I am trying to build a simple contact form. When I host the website on my local server the ajax posts the data to the PHP file, and the PHP file is able to get the information. But when I host the website on my host's server the PHP file isn't able to access the posted data. I'm not quite sure why.
JQuery/Ajax:
$(document).ready(function() {
$("#contactFormToSubmit").submit(function(e) {
e.preventDefault();
let fullname = $("#nameForm")
.val()
.trim();
let subject = $("#subjForm")
.val()
.trim();
let email = $("#emailForm")
.val()
.trim();
let message = $("#textForm")
.val()
.trim();
let new_form = new FormData();
new_form.append("fullname", fullname);
new_form.append("subject", subject);
new_form.append("emailFrom", email);
new_form.append("message", message);
$.ajax({
type: "POST",
url: "contactFormPHP/submitform.php",
data: new_form,
contentType: false,
processData: false,
cache: false,
success: function() {
$("#FormSubmitDiv").append(
'<div class="alert alert-success text-center alert-dismissible fade show" role="alert"><strong>Submitted successfully! Thank you.</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>'
);
$(".alert-success").fadeOut(10000);
$("#contactFormToSubmit")[0].reset();
}
});
});
});
and PHP:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'config.php';
require 'plugins/PHPMailer/src/Exception.php';
require 'plugins/PHPMailer/src/PHPMailer.php';
require 'plugins/PHPMailer/src/SMTP.php';
$to = '*********#gmail.com';
if(isset($_POST['fullname'])){
echo "<script>console.log('It is working properly!');</script>";
}
if(!isset($_POST['fullname'])){
echo "<script>console.log('It is not working properly!');</script>";
}
$fullname = $_POST['fullname'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$email_from = $_POST['emailFrom'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "From: " .$email_from. "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
function console_log($fullname, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($fullname, JSON_HEX_TAG) .
');';
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}
$mail = new PHPMailer(true);
try {
$mail->STMPOptions = array(
'ssl'=> array(
'verify_peer'=> false,
'verify_peer_name'=> false,
'allow_self_signed'=> true,
)
);
$mail->isSMTP();
$mail->SMTPDebug = 2; // Send using SMTP
$mail->Host = CONFIG['email']['host']; // Set the SMTP server to send through
$mail->SMTPAuth = true;
$mail->Port = CONFIG['email']['port']; // Enable SMTP authentication
$mail->SMTPSecure = CONFIG['email']['SMTPSecure']; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Username = CONFIG['email']['username']; // SMTP username
$mail->Password = CONFIG['email']['password']; // SMTP password
//Recipients
$mail->AddReplyTo($email_from, $fullname);
$mail->setFrom($email_from, $fullname);
$mail->addAddress($to, 'Blue Owl Learning');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
$mail->send();
echo 'Message has been sent';
}
catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
I was using the .htaccess to change the links. So although there was no clear syntax error, the link I was using was slightly wrong, so changing the url from
url: "contactFormPHP/submitform.php"
to
url: "contactFormPHP/submitform"
fixed the problem
I'm trying to send an email with PHPMailer, but everytime I press to send, the page turns white. I tried to search in the error_log but nothing appeared inside. By the way, I'm using ajax, all the plugins are included and working.
This is the code I have:
$.ajax({
type: "POST",
url: "cod_ajax/enviar_email.php",
data: "nome="+nome+"&last="+last+"&email="+email+"&assunto="+assunto+"&texto="+texto,
success:function(e){
document.write(e);
$("#envia_email").prop("disabled", true);
setInterval(function(){
$("#envia_email").html("Email Enviado com sucesso! Recarregue a página para enviar outro!");
}, 2000);
$(".erros").fadeOut(0);
$("#name").val("");
$("#last").val("");
$("#email").val("");
$("#assunto").val("");
$("#texto").val("");
}
})
All variables are right, nothing is empty and receive well the information. This is my ajax file:
if(isset($_POST['name'])){
$nome=$_POST['nome'];
$last=$_POST['last'];
$email=$_POST['email'];
$assunto=$_POST['assunto'];
$texto=$_POST['texto'];
require '../mail/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('b_daniel_18#hotmail.com');
$mail->addAddress('b_sem_l#hotmail.com');
$mail->Subject = 'First PHPMailer Message';
$mail->Body = 'Hi! This is my first e-mail sent through PHPMailer.';
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
}
I didn't use the variables because it didn't work so I tried adding information manually, still didn't work.
UPDATE
Removed the if(isset($_POST['name'])) and I can see the errors now. It doesn't send, appears Mailer error: Could not instantiate mail function.
You mistyped your form variable name in the php file. Change
if(isset($_POST['name']))
To:
if(isset($_POST['nome']))
Try this code
$mail = new PHPMailer();
$mail->SMTPSecure = 'tls';
$mail->Username = "b_daniel_18#hotmail.com";
$mail->Password = "mypassword";
$mail->AddAddress("b_sem_l#hotmail.com");
$mail->FromName = "My Name";
$mail->Subject = "My Subject";
$mail->Body = "My Body";
$mail->Host = "smtp.live.com";
$mail->Port = 587;
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->From = $mail->Username;
if($mail->Send()){
echo 'Sent.<br/>';
}else{
echo 'Not sent: <pre>'.print_r(error_get_last(), true).'</pre>';
}
How I can show success message after to click send in my form? my phpmailer is working but I want to also after to click send to redirect to my homepage (index.html) and show my message div. This is my php code.
<?php
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$subject = $_POST['subject'];
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.xxxxxxx.pl'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxx#xxxxxxxx.pl'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom($email, $name);
$mail->addAddress('xxxx#gmail.com', 'xxxxxxxx'); // Add a recipient // Name is optional
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = 'Body test';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
header('Location: index.html');
}
And this is my Jquery code to show/hidden div succes:
$('.box-up').animate({top : 150}, 'normal').delay(3000).animate({top : -500}, 'normal');
You could send extra parameter with your request :
header('Location: index.php?r=1');
Then in your index page get the parameter and use it to show the box :
<script>
var result="<?php echo $_GET['r']; ?>";
if(parseInt(result)){
$('.box-up').animate({top : 150}, 'normal').delay(3000).animate({top : -500}, 'normal');
}
</script>
Hope this helps.
I am building a bulk email tool to address a list of our clients regarding some upcoming migrations. Our current mass mail tool doesn't quite cut it in this particular case, where I have opted to just build one instead.
I am using TinyMCE to provide an editor for the email message body and passing this along to PHPMailer to send out. Everything is working great except the html is not displayed properly when viewed in a client such as Outlook. I have made absolutely sure $mail->isHTML(true) is set so I am at a loss now.
I echo out the value of $message in the bulk_mail_sender() function and its correct. If I paste this string as $mail->Body it works. If I have $message set as $mail->Body however, it turns into all sorts of strange characters.
Message Source:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><p>Hi there,</p>
<p>Â </p>
<p>What is up foo</p>
Code:
function bulk_mail_sender($vars, $emails, $subject, $message)
{
foreach ($emails as $email)
{
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $vars['opt_host']; // Specify main SMTP Server
$mail->Port = $vars['opt_port']; // TCP port
$mail->Username = $vars['opt_user']; // SMTP Username
$mail->Password = $vars['opt_pass']; // SMTP Password
$mail->SMTPSecure = $vars['opt_type']; // Enable TLS / SSL encryption
$mail->setFrom($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addAddress($email);
$mail->addReplyTo($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
if(!$mail->send())
{
echo 'Message failed to send to ' . $email;
echo 'Mailer Error: ' . $mail->ErrorInfo . '</br></br>';
}
else
{
echo 'Message has been sent to ' . $email . '</br>';
}
}
}
function bulk_mail_output($vars)
{
if (!empty($_POST))
{
$subject = $_POST['subject'];
$message = $_POST['message'];
$emails = $_POST['emails'];
$emails = explode(PHP_EOL, $emails);
bulk_mail_sender($vars, $emails, $subject, $message);
}
else
{
echo '<form method="POST" action="">';
echo 'Subject: <input type="text" name="subject" id="subject"></br></br>';
echo '<textarea rows="10" cols="100" name="message" id="message"></textarea></br></br>';
echo '<h3>Email Addresses</h3>';
echo '<textarea rows="10" cols="100" name="emails" id="emails"></textarea></br></br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
echo '<script language="javascript" type="text/javascript" src="../includes/jscript/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
mode: "exact",
elements: "message",
theme: "advanced",
entity_encoding: "raw",
convert_urls: false,
relative_urls: false,
plugins: "style,table,advlink,inlinepopups,media,searchreplace,contextmenu,paste,directionality,visualchars,xhtmlxtras",
theme_advanced_buttons1: "cut,copy,paste,pastetext,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,search,replace",
theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,forecolor,backcolor,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media,|,ltr,rtl,cleanup,code,help",
theme_advanced_buttons3: "", // tablecontrols
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true
});
function toggleEditor(id)
{
if (!tinyMCE.get(id))
tinyMCE.execCommand(\'mceAddControl\', false, id);
else
tinyMCE.execCommand(\'mceRemoveControl\', false, id);
}
</script>';
}
}
While I couldn't ever find a way to fix this within TinyMCE, the workaround used was to just wrap my $message variable in the html_entity_decode function when setting it to the mail body. I would have preferred to pass the data from TinyMCE properly the first time, however the entity encoding cannot be fully disabled for some reason.
$mail = new PHPMailer;
$mail->CharSet = "UTF-8";
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $vars['opt_host']; // Specify main SMTP Server
$mail->Port = $vars['opt_port']; // TCP port
$mail->Username = $vars['opt_user']; // SMTP Username
$mail->Password = $vars['opt_pass']; // SMTP Password
$mail->SMTPSecure = $vars['opt_type']; // Enable TLS / SSL encryption
$mail->setFrom($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addReplyTo($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addAddress($email);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = html_entity_decode($message);
if(!$mail->send())
{
echo 'Message failed to send to ' . $email;
echo 'Mailer Error: ' . $mail->ErrorInfo . '</br></br>';
}
else
{
echo 'Message has been sent to ' . $email . '</br>';
}
I have a little problem with an iOS cordova Webapp and PHP. The code below works perfectly on the computer(Xampp):
<?php
require 'lib/sendMail.php';
require '../php/PHPMailerAutoload.php';
$mail = new PHPMailer;
$sendMail = new sendMail();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'ex#ex.de';
$mail->Password = 'expw';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From = 'ex#ex.com';
$mail->FromName = 'Mailer';
$mail->addAddress($_POST['termin']['cityemail']);
$mail->isHTML(true);
$mail->Subject = 'ex';
$mail->Body = $sendMail->getMessage($_POST);
$mail->AltBody = $sendMail->getMessage($_POST);
if(!$mail->send()) {
print 'Message could not be sent.';
print 'Mailer Error: ' . $mail->ErrorInfo;
} else {
print 'Message has been sent';
}
?>
Note: I am using PhpMailer to send mails via the phone.
The problem is, that the phone is going crazy. Everything after "->" is ignored or something. This is how the screen looks after submitting the form:
How can this happen? The email is sending successfully on the browser.
The device is iPhone 5S 16GB with iOS 8.1.
Okay I've got a working solution. Simply put your php files on a server, make an ajax call with type = " post " and there you go. Example code below(I'm using jQuery validation plugin) :
$("#Formular").validate({
submitHandler: function(form) {
var dataString = $(form).serialize();
$.ajax(
{
url : 'http://yoururl.de/file.php',
type: "POST",
data : dataString,
success:function(data, textStatus, jqXHR)
{
$('body').html(data);
}
});
},
rules: {
'phone': {
required: false,
phoneDE: true
}
},
messages: {
'phone': {
required: "Bitte gültige Telefonnummer eingeben"
}
}
});