0
<html>
<body>
<button type="button" onclick="myFunc()">Click</button>
</body>
</html>
<?php
    function myFunc() {
        echo "Hello world";
    }
?>

I made a code like that and tested it but nothing happened. So is it even possible to do it like that or should I just use JavaScript instead?

2 Answers 2

4

Use javascript instead. PHP is not meant to do that.

PHP runs on server side but javascript runs on client side.

<html>
<head>
    <script>
        function myFunc(){
            document.getElementById('content').innerHTML = "Hello world";
        }
    </script>
</head>
<body>
<button type="button" onclick="myFunc()">Click</button><div id="content"></div>
</body>
</html>

jsFiddle

To understand it simply, the PHP interpreter first pre-process your PHP file (hence its name - PHP: Hypertext Preprocessor), and interpret anything inside <?php and ?> tags and turn it into HTML, response header, and so on...

In your case, you define a PHP function and that's all. The function is unused - but the interpreter doesn't care.

After that, the server sends the preprocessed HTML to client side, and anything inside PHP tags are stripped.

Client (mostly, web browsers) will then parse the HTML as is. Client does not receive any PHP at all as they are gone before they are sent, and of course, the browser won't see your PHP function.

And yes, if the PHP depends on client input, you have to use form submission, Ajax, or anything like that.

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

Comments

0

You have to do JavaScript for this, all PHP code is only executed on server-side.

If you need some dynamic information from a PHP file you have to call it via Ajax (so again JavaScript)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.