Send wp post title on an email with onclick function

I am sending an email to my outlook account every time the <a> is clicked. I want that the message has the title of the wordpress post where the link was clicked, however, it is not printed in the email. It’s not recognizing the_title(); to get post title. Other problem is that the email is going into the spam folder.

how to fix this?

<a href="#" onclick="callFunction();">Report</a>
<script type="text/javascript">
    function callFunction(){
        <?php  
            $message = ''.the_title();
            $to = "my@outlook.com";
            $subject = "Expired post report";
            $from = "reporting@website.com"; 
            $headers = "From:" . $from;
            mail($to,$subject,$message,$headers); 
        ?>
    }
</script>

Related posts

Leave a Reply

1 comment

  1. For Javascript, client side execution, to call a PHP function, a server side execution, you will need to create a very small API using ajax. If you include jQuery into your project, you could send Javascript variables to a PHP file and send the mail using PHP.

    Javascript:

    $.ajax({
        type: "POST",
        url: "path/to/file/mail.php",
        data: {
            message : "<?php echo the_title(); ?>",
            subject : "Expired post report"
        }
    }).done(function( msg ) {
        alert( msg );
    });
    

    PHP file called mail.php:

    $message = $_REQUEST['message'];
    $to = "my@outlook.com",
    $subject = $_REQUEST['subject'];
    $headers = "From: reporting@website.com";
    
    echo mail($to, $subject, $message, $headers); 
    

    mail() returns true if it was successful, so the Javascript function will alert true / false.