Search code examples
phpjqueryweb-servicespostphpmailer

Error showing json_encode alert with phpmailer


I have one function post in my jquery file, that insert data into database and send one mail. That work fine without the phpmailer, showing alert, but when i put the phpmailer code alert dont work(but insert into database and send email), someone knows why this happen, and sory for bad english, thx for the help.

Update: I already get the alert changing json_encode to return on webservice and changing the alert(response); to return alert(response); on post code, but need to put an alert after close the post method, if dont do that the return alert dont appers, some idea why need that second alert after method post to get the return, thx.

My post code

$.post('insert',{val: message,name: $("#firstName").val(),desktop_id: $("#desktop_id").val(),permis: $("#permis").val(),phone: $("#phone").val(),mail: $("#mail").val()}, function (response) {
    //feedback
    alert(response);
});

My webservice

$app->post('/insert', function(){
require_once('db/dbconnect.php');
$name = $_POST['name'];
$phone= $_POST['phone'];
$phone=(int)$phone;
$mail =$_POST['mail'];
$desktop_id = $_POST['desktop_id'];
$desktop_id=(int)$desktop_id;
$permis=$_POST['permis'];
$date = date("Y-m-d");
$data=array("name"=>$name,"phone"=>$phone,"mail"=>$mail,"desktop_id"=>$desktop_id,"permis"=>$permis,"date"=>$date);
$client=$db->client();
$result = $client->insert($data);
if($result){
$response = 'Success';
}
else{
$response = 'Error';
}
//I remove the variables data
include_once("phpmailer/PHPMailerAutoload.php");

$To = $destinatarios;
$Subject = $assunto;
$Message = $value;
$Host = 'mail.'.substr(strstr($usuario, '@'), 1);
$Username = $usuario;
$Password = $senha;
$Port = "587";
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$body = $Message;

$mail-> IsSMTP(); // telling the class to use SMTP

$mail-> Host = $Host; // SMTP server

$mail-> SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only

$mail-> SMTPAuth = true; // enable SMTP authentication

$mail-> Port = $Port; // set the SMTP port for the service   server

$mail->addAttachment('mpdf/temp/doc.pdf');

$mail-> Username = $Username; // account username 

$mail-> Password = $Password; // account password

$mail-> SetFrom($usuario, $nomeDestinatario);
$mail-> Subject = $Subject;
$mail-> MsgHTML($body);
$mail-> AddAddress($To, "");
if(!$mail-> Send())
{
}
else 
{
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
});

Solution

  • When you set $response = 'Error: '. print($mail->ErrorInfo); or $response = 'Success', and then echo json_encode($response, JSON_UNESCAPED_UNICODE), you look like you are trying to turn an improperly formatted string into JSON.