I'm using PhpMailer to send emails from a php/Javascript and it's working BUT is not returning the success: function(response)
.
My javascript:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.pendente').click(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'send_email.php',
async: true,
data: dados,
context: this,
success: function(response) {
alert("Ok!");
$(this).removeClass('btn-default').addClass('btn-warning');
}
});
});
My send_email.php:
<?php
include "ligacao.php"; //connection string to BD
$encweb = $_POST['enc'];
$datapendente = date("Y-m-d H:i:s");
$texto = "'Pendente em ".$datapendente;
$texto = $texto."'";
$sql="UPDATE Texoleo.dbo.bo set bo.logi2=0, bo.logi4=1 ";
$sql=$sql.", bo.dataopen='".$datapendente."', bo.u_msgshist=";
$sql=$sql." concat(".$texto.", char(13)+char(10))+(cast(bo.u_msgshist as nvarchar(600))) ";
$sql=$sql." where bo.fref='".$encweb."'";
$result = odbc_exec($connect, $sql);
/**** Fim sql ****/
/**** Enviar email ****/
$clientenome = $_POST['nome'];
$clienteemail = $_POST['email'];
include('lib/class.phpmailer.php');
include('lib/class.smtp.php');
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'myhost.com';
$mail->SMTPAuth = true;
$mail->Username ='user@user.com';
$mail->Password = 'mypassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('my@email.com', 'Me');
$mail->addAddress('customer email', 'Customer name');
$mail->isHTML(true);
$texto = 'bla, bla, bla ';
$mail->Subject = 'My subject';
$mail->Body = $texto;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
};
$response = array("success" => true);
echo json_encode($response);
?>
Testing the same Javascript without the $mail->send()
it returns success true, but with $mail->send()
it does what it has to do (some SQL updates and email sent) but it doesn't return the success true
to continue doing the Javascript code.
As in my comment:
The debug output is messing with the JSON format. Disable it by setting SMTPDebug = 0
, and remove any other non-JSON output too.
You can usually see this kind of thing happening if you inspect the responses to your XHR requests in your browser’s dev tools.