繁体   English   中英

Jquery ajax 没有得到 PHP 的 json 响应

[英]Jquery ajax not getting json response from PHP

使用相同的逻辑一切正常,但使用 PHP mail()。 现在我用 PHPMailer 替换了它,当脚本发送 email 时,我没有收到 json 响应。

Javascript 代码:

        $("#forma_contacto").submit(function(e) {
        $.ajax({
            type: 'POST',
            url: "contact.php",
            data: $("#forma_contacto").serialize()
        }).done(function(respuesta) {
            console.log(respuesta);
            $(".resultado-contacto").html(respuesta.mensaje);
            if(respuesta.resultado == 'enviado'){
                $(".contact-form-area")[0].reset();
            }
        });
        e.preventDefault();
    });

PHP 代码:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/PHPMailer/Exception.php';
require 'vendor/PHPMailer/PHPMailer.php';
require 'vendor/PHPMailer/SMTP.php';

$sendTo = "xxx@xxxxxx.com";

$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$city = $_POST['city'];

$respuesta = array('resultado' => FALSE);

header('Content-Type: application/json; charset=utf-8');

if($city != '')
{
    $respuesta['mensaje'] = "<div class='alert alert-danger'>No se permiten bots</div>";
    echo json_encode($respuesta);
    exit(); 
}
if ($name == "")
{
    $respuesta['mensaje'] = "<div class='alert alert-danger'>Por favor dinos tu nombre</div>";
    echo json_encode($respuesta);
    exit();
}
if ($email == "")
{
    $respuesta['mensaje'] = "<div class='alert alert-danger'>Es necesario tu correo electrónico</div>"; 
    echo json_encode($respuesta);
    exit();
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    $respuesta['mensaje'] = "<div class='alert alert-danger'>El correo es inválido</div>";
    echo json_encode($respuesta);
    exit();
}
if ($message == "")
{
    $respuesta['mensaje'] = "<div class='alert alert-danger'>Por favor escribe tu mensaje</div>";
    echo json_encode($respuesta);
    exit();
}
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
    $respuesta['mensaje'] = "<div class='alert alert-danger'>Solo se permiten letras y espacios para tu nombre</div>";
    echo json_encode($respuesta);
    exit();
}

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->CharSet = 'UTF-8';
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    $mail->isSMTP();                      
    $mail->Host       = 'xxx.xxxx.xxx';
    $mail->SMTPAuth   = true;        
    $mail->Username   = '**************';
    $mail->Password   = '*************';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;                           

    //Recipients
    $mail->setFrom($sendTo);
    $mail->addAddress($sendTo);
    $mail->addReplyTo($email, $name);

    //Content
    $mail->isHTML(true);                                  
    $mail->Subject = $subject;
    $mail->Body    = $message;
    $mail->AltBody = $message;

    if($mail->send())
    {
        $respuesta['mensaje'] = "<div class='alert alert-success'>Mensaje enviado exitósamente.</div>";    
        $respuesta['resultado'] = 'enviado';        
    } else {
        $respuesta['mensaje'] = "<div class='alert alert-danger'>Ocurrió un error y el mensaje no fué enviado. Intena nuevamente.</div>";
        $respuesta['resultado'] = 'error';      
    }
} catch (Exception $e) {
    $respuesta['mensaje'] = "<div class='alert alert-danger'>Ocurrió un error y el mensaje no fué enviado.</div>";
    $respuesta['resultado'] = $mail->ErrorInfo;
    error_log($mail->ErrorInfo);
} finally {
    echo json_encode($respuesta);
    exit();
}

如果我故意运行未通过表单验证的测试,我会得到所有 json 响应。 但不是当 email 被正确发送时。 我在 javascript 方面一无所获。

有任何想法吗? 我很确定这会很简单,但我的思绪不再。

那好吧。 它现在正在工作。 我做了太多的测试,以至于我忘记了真正的解决方案是什么。

但是,我的主要怀疑是 PHPMailer 的 DEBUG 功能处于打开状态,它在发送 email 时“污染”了“echo”(json)。 所以,我把它关掉了。

$mail->SMTPDebug = SMTP::DEBUG_OFF

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM