Carol.Kar
Carol.Kar

Reputation: 5215

After button submit, refresh page

I am using wordpress version 4.9.8 and PHP 7.1.8.

Below you can see, that I have added a button to my post. This button inserts content into the_content field of a post. After submitting the button I would like to refresh the single post page and show the content.

Find below my code for the button:

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_updateContent', 'updateContent');
function updateContent()
{

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

    try {
        $sp = new SinglePostContent();
        $sp->main($post_id);
    } catch (Exception $e) {
        echo $e;
    }
    wp_die(); // this is required to terminate immediately and return a proper response
}

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
                };
                // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
                jQuery.post(ajaxurl, data, function (response) {
                    console.log("test12")
                    console.log(response);
                });
            });
        });
    </script>

    <?php
}

Any suggestions how to refresh the page and show the content.

Looking forward to your replies!

Upvotes: 1

Views: 69

Answers (3)

Ash0ur
Ash0ur

Reputation: 1545

           jQuery.post(ajaxurl, data, function (response) {
                console.log("test12")
                console.log(response);
                location.reload(true);
            });

use ture in reload to make a hard refresh reload from the server. or you can return the updated post content and use html() to replace it without a refresh.

Upvotes: 1

Arash Hasanzade
Arash Hasanzade

Reputation: 490

Change your code like this :

[...]
jQuery.post(ajaxurl, data, function (response) {
  console.log("test12")
  console.log(response);
  window.location.reload();
});
[...]

Upvotes: 1

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11121

in callback function, reload the page:

jQuery.post(ajaxurl, data, function (response) {
    console.log("test12")
    console.log(response);
    location.reload();
});

Upvotes: 1

Related Questions