I am loading the personalizetest.php
(It has swiftmailer code to send an email) on click event. When I load it by clicking on the button in an html file with jquery code as given below, it works, and send an email. But when I add the same code in a php file in WordPress, and I click on the button, it says “action performed successfully” in console but I don’t get any email.
I searched a bit and find that I have to add following code in function.php to execute the file on WordPress which I did but now it is sending email on every page refresh. Either I open website or go from one page to another and not on button click. In short, I am loading this personalizetest.php
file when I click the button with class=button
:
function.php
<?php
function enqueue_scripts_styles_init() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'./personalizetest.php', array('jquery'), 1.0 ); // jQuery will be included automatically
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
}
add_action('init', 'enqueue_scripts_styles_init');
?>
jQuery code
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'personalizetest.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
console.log("action performed successfully");
});
});
<input type="submit" class="button" name="insert" value="insert" />
personalizetest.php (Swiftmailer code)
<?php
require_once '/lib/config.php';
require_once 'MyDecoratortest.php';
function send_my_mail() {
try {
//connect to database
$conn = new mysqli($root, $dbun, $dbps, $dbnm);
//get receipents
$recipients =[];
$sql = 'SELECT email, firstname, order_id, FROM order_details order by _id desc limit 0, 1';
$result = $conn->query($sql);
$i = 0;
while ($row = $result->fetch_assoc()) {
$recipients[$i]['email'] = $row['email'];
$recipients[$i]['firstname'] = $row['firstname'];
$recipients[$i]['order_id'] = $row['order_id'];
$i++;
}
// create the transport
$transport = Swift_SmtpTransport::newInstance($smtp_server, 587, 'tls')
->setUsername($username)
->setPassword($password);
$mailer = Swift_Mailer::newInstance($transport);
// create and register decorator
$decorator = new Swift_Plugins_DecoratorPlugin(new MyDecorator($conn));
$mailer->registerPlugin($decorator);
//email
$html_message="My email text";
// prepare email message
$message = Swift_Message::newInstance()
->setSubject('Your Order at Dissertation Sage -- #order_id')
->setFrom($from)
->setBcc($bcc)
->setBody($html_message, 'text/html');
// tracking variables
$sent = 0;
$failures = [];
// send the personalized message to each recipient
foreach ($recipients as $recipient) {
$message->setTo([$recipient['email'] => $recipient['firstname']]);
$sent += $mailer->send($message);
}
// display result
if ($sent) {
echo "Number of emails sent: $sent<br>";
}
if ($failures) {
echo "Couldn't send to the following addresses:<br>";
foreach ($failures as $failure) {
echo $failure . '<br>';
}
}
} catch (Exception $e) {
echo $e->getMessage();
}}?>
First of all you included
.php
in yourwp_enqueue_script
. This just won’t do. If your ajax callback function is in apersonalizetest.php
file, you need to include it usingThe script enqueued here is called
custom.js
but you can set this to what ever script you’re using to call your ajax call in.The js part should look like (in your
custom.js
equivalent):The action should point to the ajax callback function located in
personalizetest.php
file using hooks:(change the name of the action ofc).
You can read the blog post I made about ajax loading, it’s for posts, but the same principle applies here:
AJAX load posts on WordPress