0

I am using wordpress 4.9.8 and PHP 7.1.8 I have added a button to the new post screen:

enter image description here

I am trying to trigger the button the following way:

add_action( 'media_buttons', 'add_my_media_button', 99 );
function add_my_media_button() {

    $post = $GLOBALS['post_ID'];
    echo "<a href='#' id='insert-my-media' data-post-id='{$post}' class='button'>Own content</a>";

}

add_action( 'wp_ajax_my_action', 'updateContent' );
function updateContent() {

    $post_id = intval( $_POST['post_id'] );

    wp_die(); // this is required to terminate immediately and return a proper response
    $post = array(
        'ID'           => $post_id,
        'post_content' => 'Insert this content',
    );

    // Update the post into the database
    wp_update_post( $post );
}

add_action( 'admin_footer', 'my_media_button_script' );
function my_media_button_script() {

    ?>
    <script>
        jQuery(document).ready(function ($) {
            $('#insert-my-media').click(function () {
                var post_id = $(this).attr('data-post-id');
                var data = {
                    'action': 'updateContent',
                    'post_id': post_id
                };
                console.log("test: " + ajaxurl)
                console.log(data)
                // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
                jQuery.post(ajaxurl, data, function (response) {
                    alert('Got this from the server: ' + response);
                });
            });
        });
    </script>

    <?php
}

However, when pressing submit I get:

enter image description here

Any suggestions why I get this error.

The above code was partly taken from the official reference.

0

Remove this line

add_action( 'wp_ajax_my_action', 'updateContent' );

Add this two Line

add_action( 'wp_ajax_nopriv_updateContent', 'updateContent' );
add_action( 'wp_ajax_updateContent', 'updateContent' );

hopefully it will solve your issue

https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)

  • Could you update your answer with an example? – Howdy_McGee Jul 19 at 14:35
  • Sure I will update my answer as soon as I can – Ahadul Jul 19 at 14:36
  • Code Example added ! @Howdy_McGee thanks . – Ahadul Jul 19 at 16:41
  • @Ahadul Thanks for your answer & update, +1 – Howdy_McGee Jul 19 at 16:50
-1

Replace this add_action( 'wp_ajax_my_action', 'updateContent' );

with

add_action( 'wp_ajax_updateContent', 'updateContent' ); add_action( 'wp_ajax_nopriv_updateContent', 'updateContent' );

Happy codeing

New contributor
vikas jain is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.