2

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>";
}
?>
  • 2
    You can not execute PHP code with a button click without an HTTP request. Try using the jQuery GET/POST method. – Mohamed Shahid Dec 01 '20 at 12:24
  • can you suggest a sample code for that. – shekhar singhal Dec 04 '20 at 09:35
  • @shekharsinghal Have you researched anything before asking for code to be written *for* you? There are [plenty](https://stackoverflow.com/questions/1280767/how-do-i-run-php-code-when-a-user-clicks-on-a-link) [of](https://stackoverflow.com/questions/16548007/execute-php-from-javascript) [relevant](https://stackoverflow.com/questions/15757750/how-can-i-call-php-functions-by-javascript) [resources](https://stackoverflow.com/questions/1045845/how-to-call-a-javascript-function-from-php) on this very topic already on Stack Overflow. – esqew Dec 04 '20 at 13:16
  • @esqew : I have tried most off all the available examples. I am trying this since last 5-6 days but nothing helped. that's why i am looking for the example code that someone have tried himself. – shekhar singhal Dec 05 '20 at 05:26

1 Answers1

1

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>
Mohamed Shahid
  • 476
  • 5
  • 18