skip to Main Content

I’m trying to get a form to work on an admin page on WordPress. I want to be able to input an email address and have it send an email to the email inputted. I’m using a jQuery Ajax function to send the info from the form to the PHP that I am using to send the email. Everything is in a custom WordPress plugin. The code worked when I was testing it in a normal page on WordPress, but since I moved it to an admin page in the plug in, I can’t seem to get it to work.

The JavaScript file 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
        });
    });
});

The PHP code:

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');

I’ve tried about everything I can think of with no success. I would appreciate any feedback or suggestions for things I might try.

2

Answers


  1. Have you ever tried this approach?
    https://stackoverflow.com/a/26781019/9855327

    Just be aware where you are adding this script because you can loose this code after the WP version is updated.

    Login or Signup to reply.
  2. For admin side, you need to replace wp_enqueue_scripts hook as it only works on front end.

    I have revisited your code

    JavaScript file 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);
            });
        }
    });
    

    Then the php code:

    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');
    

    Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search