javascriptwordpressemailfetchwp-mail

Send email via wp_mail in WordPress using JavaScript fetch


I created small react app which i use inside homepage header in oxygen builder (wordpress) and i need to send notification to owners email.

Buton triggers function:

<button onClick={submitMail}>Send email to owner</button>

The function:

const submitMail = async () => { 

const rawResponse = await fetch('https://mywordpressinstallation.com/wp-admin/admin-ajax.php?action=mail_before_submit', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({to: 'my-email@gmail.com', title: 'Some title', text: 'some text'}),
//i would like to get something back but i get nothing
    success: function(data, textStatus, jqXHR) { 
            console.log(data)
           console.log(textStatus)
        }
 });
  const content = await rawResponse;
//returns promise, status fullfiled
}

Then via code snippet plugin i created function:

add_action('wp_ajax_nopriv_mail_before_submit', 'mail_before_submit');
add_action('wp_ajax_mail_before_submit', 'mail_before_submit');
function mail_before_submit() {
     $to     = $_POST['to'];
   $title = $_POST['title'];
    $text = $_POST['text'];

    wp_mail($to, $title, 'body text');
    return 'email sent';
    die();
}

And it's not working. But If i put

wp_mail('some-email@gmail.com', 'title', 'text')

its working! So i am on good track. The email is sent to that address, with subject "title" and message "text". But if i use variables $to, $title and $text - nothing.

I am realy streaching what i know with this. I built a house of cards. Please advise.

Kind regards, Ivanko

I want to send email using wordpress, manualy call php function from javascript which sends mail via wp_mail()


Solution

  • if you post json to PHP it won't show up in the $_POST global. Use a FormData instead with a normal 'application/x-www-form-urlencoded; charset=UTF-8' post

    const data = new FormData();
    data.append( 'action', 'mail_before_submit' );
    data.append( 'to', 'my-email@gmail.com' );
    data.append( 'title', 'Some title');
    data.append( 'text', 'Some text' );
    
    const rawResponse = await fetch('https://mywordpressinstallation.com/wp-admin/admin-ajax.php', {
        method: 'POST',
        body: data,
    });