在管理中加入 jQuery 脚本,以在自定义 WordPress 插件中通过 ajax 发送电子邮件

问题描述 投票:0回答:2

我正在尝试获取一个可在 WordPress 管理页面上使用的表单。我希望能够输入一个电子邮件地址并让它向输入的电子邮件地址发送一封电子邮件。我正在使用 jQuery ajax 函数将信息从表单发送到我用来发送电子邮件的 php。一切都在自定义 WordPress 插件中。当我在 WordPress 中测试它的普通页面时,该代码有效,但自从我将它移动到插件中的管理页面后,我似乎无法让它工作。

at_home-welcome-rev2.js

jQuery(document).ready(function ($) {
    $('#at_home_form').on('submit', function (event) {
        event.preventDefault(); // Prevent the default form submission
        
        var emailInput = $('#userEmailInput').val(); // Get the user's email input
        var nonce = ajax_object.nonce
        console.log(nonce);
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'send_email', // Use the updated action name
                user_email: emailInput, // Pass the user's email input
                nonce: nonce
            },
            
            success: function (response) {
                alert('Email sent successfully!');
            },
            error: function (error) {
                alert('Error sending email: ' + error.responseText);
            }
            
        });
        console.log('Data array:', {
            action: 'send_email',
            user_email: emailInput
        });
    });
});

我的PHP代码

function enqueue_plugin_scripts() {
    // Enqueue your JavaScript file
    wp_enqueue_script('at_home_welcome', plugin_dir_url(__FILE__) . 'js/at-home-welcome-rev2.js', array('jquery'), '1.0', true);

    // Localize the script with data
    wp_localize_script('at_home_welcome', 'ajax_admin_object', array(
        'ajax_url' => admin_url('admin-ajax.php'), // Default AJAX URL
        'nonce' => wp_create_nonce('at_home_welcome-nonce') // Create a nonce for security
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_plugin_scripts');
function at_home_menu_page() {
    add_menu_page(
        'At Home Care Certification Form', // Page title
        'AT Home Care', // Menu title
        'manage_options', // Capability required to access
        'at-home-care', // Menu slug
        'at_home_care_settings_page_callback' // Callback function to display content
    );
}
add_action('admin_menu', 'at_home_menu_page');

function at_home_care_settings_page_callback() {
    ?>
    <div class="wrap">
        <h1>Your Plugin Settings</h1>
        <form id="at_home_form">
            <label for="userEmailInput">Enter your email:</label>
            <input type="email" id="userEmailInput" name="userEmailInput" placeholder="[email protected]">
            <button type="submit" id="sendEmailButton">Send Email</button>
        </form>
    </div>
    <?php
}

// AJAX action to send email
function at_home_welcome_send_email_callback() {
    if (isset($_POST['user_email'])) {
        $to = sanitize_email($_POST['user_email']); // Sanitize the user's email input
        $subject = 'Your Membership has been approved';
        $message = 'Welcome, we hope you enjoy your membership';
        $nonce = $_POST['nonce'];
        error_log('Received email: ' . $nonce);
        // Verify nonce
        if (wp_verify_nonce($nonce, 'at-home-nonce')) {
            error_log('Received email: ' . $to); // Check the email value in PHP error log
            // Send the email
            $sent = wp_mail($to, $subject, $message);
        } else {
            wp_send_json_error();
        }

        // Return the response
        if ($sent) {
            wp_send_json_success();
        } else {
            wp_send_json_error();
        }
    } else {
        wp_send_json_error();
    }
}
add_action('wp_ajax_send_email', 'at_home_welcome_send_email_callback');
add_action('wp_ajax_send_email', 'at_home_welcome_send_email_callback');

我已经尝试了所有我能想到的方法,但没有成功。对于我可能尝试的任何反馈或建议,我将不胜感激。

javascript php jquery ajax wordpress
2个回答
0
投票

您尝试过这种方法吗? https://stackoverflow.com/a/26781019/9855327

请注意在哪里添加此脚本,因为在 WP 版本更新后您可能会丢失此代码。


0
投票

对于管理端,您需要替换

wp_enqueue_scripts
钩子,因为它仅适用于前端。

我重新审视了你的代码

JavaScript 文件 at_home-welcome-rev2.js:

jQuery( function($) {
    // check that the localized variable at_home_params is defined
    if (typeof at_home_params !== 'undefined') {
        $('#at_home_form').on('submit', function (event) {
            event.preventDefault(); // Prevent the default form submission
            const ajaxData = {
                action: 'at_home_send_email', // Use the updated action name
                user_email: $('#userEmailInput').val(), // Pass the user's email input
                nonce: at_home_params.nonce
            };
            $.ajax({
                url: at_home_params.ajax_url,
                type: 'POST',
                data: ajaxData,
                success: function(response) {
                    console.log(response);
                },
                error: function (error) {
                    console.log('Error : ' + error.responseText);
                }
            });
            // console.log(ajaxData);
        });
    }
});

然后是php代码:

function enqueue_plugin_scripts() {
    // Enqueue your JavaScript file
    wp_enqueue_script('at-home-welcome', plugin_dir_url(__FILE__) . 'js/at-home-welcome-rev2.js', array('jquery'), '1.0', true);

    // Localize the script with data
    wp_localize_script('at-home-welcome', 'at_home_params', array(
        'ajax_url' => admin_url('admin-ajax.php'), // Default AJAX URL
        'nonce' => wp_create_nonce('at_home_welcome') // Create a nonce for security
    ));
}
add_action('admin_enqueue_scripts', 'enqueue_plugin_scripts');

function at_home_menu_page() {
    add_menu_page(
        'At Home Care Certification Form', // Page title
        'AT Home Care', // Menu title
        'manage_options', // Capability required to access
        'at-home-care', // Menu slug
        'at_home_care_settings_page_callback' // Callback function to display content
    );
}
add_action('admin_menu', 'at_home_menu_page');

function at_home_care_settings_page_callback() {
    echo '<div class="wrap">
        <h1>'.__('Your Plugin Settings').'</h1>
        <form id="at_home_form">
            <label for="userEmailInput">'.__('Enter your email:').'</label>
            <input type="email" id="userEmailInput" name="userEmailInput" placeholder="[email protected]">
            <button type="submit" id="sendEmailButton">'.__('Send Email').'</button>
        </form>
    </div>';
}

// AJAX action to send email
function at_home_send_email_ajax_callback() {
    if ( isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'at_home_welcome') 
    && isset($_POST['user_email']) && !empty($_POST['user_email'])) {
        $to      = sanitize_email($_POST['user_email']); // Sanitize the user's email input
        $subject = __('Your Membership has been approved');
        $message = __('Welcome, we hope you enjoy your membership.');

        // Send email
        $sent = wp_mail($to, $subject, $message);

        error_log('Email details: ' . print_r( array(
            'to'         => $to,
            'subject'    => $subject,
            'message'    => $message,
            'Email sent' => $sent ? 'YES' : 'NO',
        ), true));

        wp_die( $sent ? __('Email sent successfully!') : __('Something went wrong :(') );
    }
    wp_die(__('An error occured.'));
}
add_action('wp_ajax_at_home_send_email', 'at_home_send_email_ajax_callback');

已测试且有效。

© www.soinside.com 2019 - 2024. All rights reserved.