Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

how can i call javascript function from controller

in test .volt i have a js function run(), i want to call it from Controller action

<html>
<body>
<h1>Test</h1>
<p>sample

 <script type="text/javascript">    

            function run(){
                alert("hello world");
            }         
       </script>

</body>
</html>
<?php
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Mvc\Model\Query;
use Phalcon\Mvc\Model\Query\Builder;
use Phalcon\Paginator\Adapter\Model as Paginator;

class SampleController extends ControllerBase
{
    public function testAction()
        {
                    i want to call  js function from here 

                ///      echo "<script> run() </script>";   //  this code is not working  

        }
}


42.8k
Accepted
answer

You cannot call JS from PHP. Google the web app basics....

In short - PHP is server side environment, and JS is client side (i.e. runs in a client browser).

Usually it is quite the opposite - you'll call back-end (PHP) from a client (JS) via AJAX or so.

You can just print out JS syntax which will be presented to the client...

 <!-- Instantiate clipboard JS -->
    <script>
        var clipboard = new Clipboard('.btn');

        clipboard.on('success', function(e) {
            alert('URL SUCCESSFULLY COPIED INTO CLIPBOARD!');
        });
        clipboard.on('error', function(e) {
            alert('JS CLIENT ERROR!');
            console.log(e);
        });
    </script>

But the actual function call will happen only when a client triggers it by click or other event.