admin管理员组

文章数量:1122846

I am sending email with phpmailer, I receive the emails when I press the "send" button, but I wanted to stay on the same HTML page, so I used AJAX script with HTML and PHP. The problem is that I am not getting the JSON data back that I need to update my HTML page with the email status and PHP reponse, so :

  • response_array status
  • response_array message
  • response_array success

Thank you for your help

AJAX IN HTML

<script>
        $("#form").submit(function(e) {
        e.preventDefault(); // prevent actual form submit
        var from_name_temp = $('#from_name').val();
        var from_email_temp = $('#from_email').val();
        var choix_gout_temp = $(".choix_gout:checked").val();
        $.ajax({
            type: "POST",
            url: "/mailer.php",
            data: "from_name="+from_name_temp+"&from_email="+from_email_temp+"&choix_gout="+choix_gout_temp,
            dataType: "json",
            complete: function(data) {
                    console.log("Thank you for subscribing!");
                    console.log(data);
                    console.log(data.status);
                    console.log(data.message);
                    console.log(data.success);
                }
        })
    });
</script>

PHP

<?php

$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';

$from_email = '';
$from_name = '';
$choix_gout = '';
$response_array = array();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
    
function clean_text($string)
{
    $string = trim($string);
    $string = stripslashes($string);
    $string = htmlspecialchars($string);
    return $string;
}

 send($from_name, $from_email, $choix_gout); 

function  send($from_name, $from_email, $choix_gout){
        
    $error = '';
            
    $ot1 = $_POST['choix_gout'];
    $ot2 = $_POST['from_name'];
    $ot3 = $_POST['from_email'];
    
    echo($ot1);
    echo($ot2);
    echo($ot3);

    if(empty($ot2))
    {
        $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
        $name = '';
    }
    else
    {
        $name = clean_text($ot2);
        if(!preg_match("/^[a-zA-Z ]*$/",$name))
        {
            $error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
        }
    }
    if(empty($ot3))
    {
        $error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
        $email = '';
    }
    else
    {
        //$email = clean_text($_POST["from_email"]);
        $email = clean_text($ot3);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL))
        {
            $error .= '<p><label class="text-danger">Invalid email format</label></p>';
        }
    }
    
    
    if($error == '')
    {
    
        require 'PHPMailer/src/Exception.php';          /* Exception class. */
        require 'PHPMailer/src/PHPMailer.php';          /* The main PHPMailer class. */
        require 'PHPMailer/src/SMTP.php';               /* SMTP class, needed if you want to use SMTP. */
        require 'PHPMailer/src/class.html2text.php';

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPDebug  = "1";
        $mail->Host       = "*****";
        $mail->Port       = "587";
        $mail->SMTPSecure = "tls";
        $mail->SMTPAuth   = "true";
        $mail->Username   = "*****";
        $mail->Password   = "*****";
        $mail->AddReplyTo("*****","****");
        $mail->From       = ("****");
        $mail->FromName   = ("***");
        $mail->AddAddress("*****,******");
        $mail->Subject  = "[GOUT] : " . $ot1 . ';' . $name . ';' . $email;
        $mail->IsHTML(true);
        $mail->Body = "
            <div style='width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 11px;'>
            </div>
        ";
        if(!$mail->Send()) {
            $message = 'Mail error: '.$mail->ErrorInfo;
            $response_array = array("success"=> false,
                                    "status" => false,
                                    "message" => $message);
            header('Content-Type: application/json');
            echo json_encode($response_array);die();
        } else {
            $message = "email sent";
            $response_array = array("success"=> true,
                                    "status" => true,
                                    "message" => $message);
            header('Content-Type: application/json');
            echo json_encode($response_array);die();
        }
    }
    else{
        $response_array = array("success"=> false,
                                "status" => false,
                                "message" => $error);
        header('Content-Type: application/json');
        echo json_encode($response_array);die();
    }?>

I am sending email with phpmailer, I receive the emails when I press the "send" button, but I wanted to stay on the same HTML page, so I used AJAX script with HTML and PHP. The problem is that I am not getting the JSON data back that I need to update my HTML page with the email status and PHP reponse, so :

  • response_array status
  • response_array message
  • response_array success

Thank you for your help

AJAX IN HTML

<script>
        $("#form").submit(function(e) {
        e.preventDefault(); // prevent actual form submit
        var from_name_temp = $('#from_name').val();
        var from_email_temp = $('#from_email').val();
        var choix_gout_temp = $(".choix_gout:checked").val();
        $.ajax({
            type: "POST",
            url: "/mailer.php",
            data: "from_name="+from_name_temp+"&from_email="+from_email_temp+"&choix_gout="+choix_gout_temp,
            dataType: "json",
            complete: function(data) {
                    console.log("Thank you for subscribing!");
                    console.log(data);
                    console.log(data.status);
                    console.log(data.message);
                    console.log(data.success);
                }
        })
    });
</script>

PHP

<?php

$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';

$from_email = '';
$from_name = '';
$choix_gout = '';
$response_array = array();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
    
function clean_text($string)
{
    $string = trim($string);
    $string = stripslashes($string);
    $string = htmlspecialchars($string);
    return $string;
}

 send($from_name, $from_email, $choix_gout); 

function  send($from_name, $from_email, $choix_gout){
        
    $error = '';
            
    $ot1 = $_POST['choix_gout'];
    $ot2 = $_POST['from_name'];
    $ot3 = $_POST['from_email'];
    
    echo($ot1);
    echo($ot2);
    echo($ot3);

    if(empty($ot2))
    {
        $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
        $name = '';
    }
    else
    {
        $name = clean_text($ot2);
        if(!preg_match("/^[a-zA-Z ]*$/",$name))
        {
            $error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
        }
    }
    if(empty($ot3))
    {
        $error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
        $email = '';
    }
    else
    {
        //$email = clean_text($_POST["from_email"]);
        $email = clean_text($ot3);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL))
        {
            $error .= '<p><label class="text-danger">Invalid email format</label></p>';
        }
    }
    
    
    if($error == '')
    {
    
        require 'PHPMailer/src/Exception.php';          /* Exception class. */
        require 'PHPMailer/src/PHPMailer.php';          /* The main PHPMailer class. */
        require 'PHPMailer/src/SMTP.php';               /* SMTP class, needed if you want to use SMTP. */
        require 'PHPMailer/src/class.html2text.php';

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPDebug  = "1";
        $mail->Host       = "*****";
        $mail->Port       = "587";
        $mail->SMTPSecure = "tls";
        $mail->SMTPAuth   = "true";
        $mail->Username   = "*****";
        $mail->Password   = "*****";
        $mail->AddReplyTo("*****","****");
        $mail->From       = ("****");
        $mail->FromName   = ("***");
        $mail->AddAddress("*****,******");
        $mail->Subject  = "[GOUT] : " . $ot1 . ';' . $name . ';' . $email;
        $mail->IsHTML(true);
        $mail->Body = "
            <div style='width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 11px;'>
            </div>
        ";
        if(!$mail->Send()) {
            $message = 'Mail error: '.$mail->ErrorInfo;
            $response_array = array("success"=> false,
                                    "status" => false,
                                    "message" => $message);
            header('Content-Type: application/json');
            echo json_encode($response_array);die();
        } else {
            $message = "email sent";
            $response_array = array("success"=> true,
                                    "status" => true,
                                    "message" => $message);
            header('Content-Type: application/json');
            echo json_encode($response_array);die();
        }
    }
    else{
        $response_array = array("success"=> false,
                                "status" => false,
                                "message" => $error);
        header('Content-Type: application/json');
        echo json_encode($response_array);die();
    }?>
Share Improve this question edited Jul 27, 2020 at 18:35 mozboz 2,6081 gold badge12 silver badges23 bronze badges asked Jul 27, 2020 at 14:16 Erwan ThomasErwan Thomas 11 bronze badge 2
  • Hi Erwan! I added an answer to your question. Hope it helps. Note that even though this is maybe in your Wordpress website this question isn't specifically related to Wordpress so might get closed, and you might better success on e.g. stackoverflow or a web development Stack Exchange site. – mozboz Commented Jul 27, 2020 at 14:46
  • 1 You shouldn't be using a standalone PHP file to recieve AJAX requests, the WP API isn't loaoded, and it's a major security problem. Use the REST API provided and register an endpoint – Tom J Nowell Commented Jul 27, 2020 at 14:48
Add a comment  | 

1 Answer 1

Reset to default 0

Going by the jQuery docs for the call you're using, it looks like maybe you want the success callback instead of complete. success gets passed the JSON directly, as you expect, but complete gets passed different stuff that you would have to look inside. Refer to the docs for more if you're sure you want to use complete

Try success like this:

$.ajax({
        type: "POST",
        url: "/mailer.php",
        data: "from_name="+from_name_temp+"&from_email="+from_email_temp+"&choix_gout="+choix_gout_temp,
        dataType: "json",
        success: function(data) {
                console.log("Thank you for subscribing!");
                console.log(data);
                console.log(data.status);
                console.log(data.message);
                console.log(data.success);
            }
    });

本文标签: jQuery ajax method does not return data