php file to load on click button

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:

Read More

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();
}}?>

Related posts

1 comment

  1. First of all you included .php in your wp_enqueue_script. This just won’t do. If your ajax callback function is in a personalizetest.php file, you need to include it using

    <?php
    
    require_once( get_template_directory(). '/{your folder name here}/personalizetest.php' );
    
    add_action('init', 'enqueue_scripts_styles_init');
    
    function enqueue_scripts_styles_init() {
        wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/custom.js', 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
     }
    
    ?>
    

    The 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):

    jQuery(document).ready(function($){
    $('.button').click(function(){
        var ajaxurl = ajax_object.ajaxurl,
        data =  {'action': 'my_action'};
        $.post(ajaxurl, data, function (response) {
            // Response div goes here.
            console.log("action performed successfully");
        });
    });
    

    The action should point to the ajax callback function located in personalizetest.php file using hooks:

    add_action( 'wp_ajax_my_action', 'my_action_callback' );
    add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
    

    (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

Comments are closed.