execute php Shortcode on button click

Viewed 623

I am trying to execute a php shortcode on button click but that is not running.

HTML button code is as follow..

<html>
<body>
<p align="center">
<button onclick="executeShortCode()">Refresh Date</button>

<script> 
function executeShortCode() {
alert("<?php echo do_shortcode('[Test_ShortCode]');?>");
}
</script>
</body>
</html>

PhP shortcode is as follow..

<?php 
add_shortcode( 'Test_ShortCode', 'refresh_time' );
function refresh_time( )
{
echo "Refresh Button Press @  " . date("Y/m/d H/i/s") . "<br>";
}
?>
1 Answers

Suppose you have a PHP function in

remote_function.php

<?php 
    
    function refresh_time( )
    {
        echo "Refresh Button Press @  " . date("Y/m/d H/i/s") . "<br>";
    }

    // call your function 
    refresh_time();
?>

Now call it using the AJAX GET method on button click as follows

<!DOCTYPE html>
<html>
<head>
    <title>Refesh date</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <button onclick="executeShortCode()">Refresh Date</button>
    <p id="date">Date here</p>
</body>

<script type="text/javascript">
    function executeShortCode()
    {
        $.ajax({
            url: 'remote_function.php',
            type: 'get',
            success:function(data){
              document.getElementById('date').innerHTML = data;
            },
            error: function(xhr, status, error) {
              console.log(error);
           },
        });
    }
</script>
</html>
Related