0

I would like to create a button, which will execute the php code when pressed. The issue here is the construction like this does not work:

<?php
    if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
    {
        func();
    }
    function func()
    {
        echo 'pressed';   
    }
?>


<form method="post">
    <input type="button" name="someAction" value="press me"/>
</form>

It gives an error: "Expected tag name. Got '?' instead"

Not surprisingly, a solution like this does not work either:

<div class="mydiv"><?php do_shortcode("[shortcode_name]");?></div>

However, the idea of using the shortcode is actually fine, but it has to run the shortcode only when the button is pressed.

I have also tried using JavaScript for the button, which worked, but I don't know an easy way to run the php code from JavaScript.

If you have any idea on how to do this, your answers will be welcome.

Just for context, I am using elementor for this, the html block to be exact.

2
  • 1
    Does the HTML block in Elementor even support PHP? You would need to check with its developers whether Elementor supports PHP at all. Sep 6, 2021 at 12:15
  • Good point, you're right you can't. I found this link that explains how to add php code using a shortcut. wpcodeus.com/how-to-add-php-code-to-elementor Sep 6, 2021 at 16:38

1 Answer 1

0

Php is a server-side language. Meaning the code is executed and the user will receive the compiled html code. The only way to execute php code as user is through 'post' or 'get' requests. So essentially loading a new page. The only workaround is using ajax to load new php code dynamically.

But it may also be that what you plan to do is possible to do with just Javascript. Echoing "pressed" is possible in Javascript using .innerHTML function. Or when you want to show a shortcode-widget on button click you could load it from the beginning and just set it to being visible on button click with Javascript and css.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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