MyNameIsAlex
MyNameIsAlex

Reputation: 1

PHP doesn't return data to Ajax when I use wp_mail()

When I just put the next code into HTML it works perfectly:

<?php
$name = 'My name';
$email = '[email protected]';
$headers = "From: [email protected]";
$to = '[email protected]';
$message = 'My message';
$subject = 'Message from Contact Form';

$send_email = wp_mail($to,$subject,$message,$headers);

if ($send_email == false) {
    echo 'this is error';
} else {
    echo 'this is success';
}
?>

It indeed works and echo 'this is success'.

But if I put it to a separate email.php and add into index.php the next Ajax code:

$(document).ready(function () {
  $(".myform").on("submit", function () {
    var form = $(this);
    $.ajax({
      url: "https://mywebsite.com/wp-content/themes/mytheme/email.php",
      method: form.attr("method"),
      data: form.serialize(),
      success: function (result) {
        console.log(result);
      },
    });
    return false;
  });
});

It already doesn't return anything. Console Log doesn't show anything. Once I change wp_mail() function into email.php to a regular mail() function - everything starts to work perfectly again and console log shows 'this is success'. Also I don't get emails when I use wp_mail() in a separate email.php with Ajax but I do get them when I use wp_mail() in index.php without Ajax.

Please let me know how to fix it. Why does it work with mail() but doesn't with wp_mail()? And why does wp_mail() work perfectly without Ajax into index.php, but doesn't with Ajax on a separate email.php?

PS: I removed all HTML forms into the code specially to simplify the code.

Upvotes: 0

Views: 25

Answers (0)

Related Questions