2

I have a html button which has an onclick method. The function which is ran onclick has a php function in but is called in JS, like below.

<script type="text/javascript">
    function Test() {
      <?php add_post_meta($post->ID, '_my_meta_key', true); ?> 
    }
</script>
<button onclick="Test()"></button>

The page this code is on is a wordpress admin page. When the page loads, the php function is ran anyway instead of waiting for the button click event. Is there a way to stop this from happening and only fire once the button is clicked.

4
  • 2
    It is not possible. You need Ajax for this. Commented Feb 19, 2016 at 11:16
  • Thanks. Is there a simple way to do something like this in Ajax? It's just that I don't know it that well. Commented Feb 19, 2016 at 11:19
  • 1
    You might want to read this Commented Feb 19, 2016 at 11:21
  • Thank you, will give it a read. Commented Feb 19, 2016 at 11:24

2 Answers 2

4

You cannot directly call a php function using a button click.But you can call Js functions on button click event. And then you can implement Ajax to call php functions.

You are using wordpress so you can use wp functions or custom coding to achieve this.

Php is server-side scripting language. Which will run only on server.

Sign up to request clarification or add additional context in comments.

Comments

1

You'll need to use AJAX. You can learn some useful things on w3school:
http://www.w3schools.com/ajax/

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.