简体   繁体   English

Jquery ajax 没有得到 PHP 的 json 响应

[英]Jquery ajax not getting json response from PHP

Everything was working right using the same logic, but with PHP mail().使用相同的逻辑一切正常,但使用 PHP mail()。 Now that I replaced it with PHPMailer I'm not getting the json response when the script sends the email.现在我用 PHPMailer 替换了它,当脚本发送 email 时,我没有收到 json 响应。

Javascript code: 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 code: 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();
}

If I run a test not passing form validations on purpose I get all the json responses alright.如果我故意运行未通过表单验证的测试,我会得到所有 json 响应。 But not when the email is sent correctly.但不是当 email 被正确发送时。 I get nothing on the javascript side.我在 javascript 方面一无所获。

Any ideas?有任何想法吗? I'm pretty sure it's going to be something simple, but my mind goes no more.我很确定这会很简单,但我的思绪不再。

Oh well.那好吧。 It's working now.它现在正在工作。 I made so many tests that I lost track of what the solution really was.我做了太多的测试,以至于我忘记了真正的解决方案是什么。

However, my main suspicion is the DEBUG feature of PHPMailer was on and it "polluted" the 'echo' (json) when email was sent.但是,我的主要怀疑是 PHPMailer 的 DEBUG 功能处于打开状态,它在发送 email 时“污染”了“echo”(json)。 So, I turned it off.所以,我把它关掉了。

$mail->SMTPDebug = SMTP::DEBUG_OFF

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

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