Sunday, November 6, 2022
HomeWordPress Developmentjquery - The best way to securely add an Ajax button to...

jquery – The best way to securely add an Ajax button to a WP Admin web page?


On this reply I created 2 buttons that are visually disabled and get an invalid nonce earlier than submitting.

<?php
/*
Plugin Identify: Ajax Instance
*/

add_action( 'admin_notices', 'my_action_button' );

outline( 'MY_ACTION_NONCE', 'my-action-' );

perform my_action_button() {
    $id   = 4321;
    $information = array(
        'data-nonce' => wp_create_nonce( MY_ACTION_NONCE . $id ),
        'data-id'    => $id,
    );
    echo get_submit_button( "Ajax Major", 'main massive', 'my-action-button-1', FALSE, $information );

    $id   += 1234;
    $information = array(
        'data-nonce' => wp_create_nonce( MY_ACTION_NONCE . $id ),
        'data-id'    => $id,
    );
    echo get_submit_button( "Ajax Secundary", 'secondary', 'my-action-button-2', FALSE, $information );
}

add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS under right here

perform my_action_javascript() {
    ?>
    <script sort="textual content/javascript">
        jQuery(doc).prepared(perform ($) {
            $('#my-action-button-1,#my-action-button-2').click on(perform () {
                var $button = $(this);

                var information = {
                    'motion': 'my_action',
                    'id': $button.information('id'),
                    'nonce': $button.information('nonce')
                };
                // Give consumer cue to not click on once more
                $button.addClass('disabled');
                // Invalidate the nonce
                $button.information('nonce', 'invalid');

                $.publish(ajaxurl, information, perform (response) {
                    alert('Received this from the server: ' + response);

                });
            });
        });
    </script>
    <?php
}

add_action( 'wp_ajax_my_action', 'my_action' );

perform my_action() {
    world $wpdb; // that is the way you get entry to the database

    $id    = $_POST['id'];
    $nonce = $_POST['nonce'];
    if ( wp_verify_nonce( $nonce, MY_ACTION_NONCE . $id ) ) {
        $response = intval( $id );
        $response += 10;
        echo $response;
    } else {
        echo - 1;
    }
    wp_die(); // that is required to terminate instantly and return a correct response
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments