1

I want testFunction() to call check() that i created in my plugin php when i click My Button. How do i make it work ?

<?php
function createButton()
{
    echo '<button onclick="testFunction()">My Button</button>';
}

function check()
{
    alert("Works");
}

function my_php_function()
{
    echo '<script>
    function testFunction() {
      check();
    }
  </script>';
}
add_action( 'wp_footer', 'my_php_function' );
2
  • 1
    You're mixing up PHP and JavaScript. check() either needs to be a JavaScript function in a .js file or between <script></script> tags, or if it needs to be a PHP function, you need to use AJAX to run the function on the server. Your code is just sample code so I can't tell what you need. Commented Jun 5, 2020 at 1:19
  • check() needs to be a PHP function. So i need to use AJAX, how do i do that ?
    – Kitiara
    Commented Jun 5, 2020 at 1:29

2 Answers 2

0

AJAX is the solution. For more info: https://codex.wordpress.org/AJAX_in_Plugins#Separate_JavaScript_File

0
0

I could not stand by and see that mangled code. Here is what I think you meant to do.

<?php
function createButton()
{
    echo '<button onclick="testFunction()">My Button</button>';
}

function my_php_function()
{
    echo '<script>
    function check()
    {
        alert("Works");
    }
    function testFunction() {
      check();
    }
  </script>';
}
add_action( 'wp_footer', 'my_php_function' );
1
  • I specifically wanted to do it without echo.
    – Kitiara
    Commented Jun 13, 2020 at 5:00

Your Answer

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

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