Reputation: 321
I have to call a javascript function from my Model or Controller. I can call it from the view file but how can I call a JS function directly from Model.
Is there a way to do that?
Upvotes: 1
Views: 1586
Reputation: 25698
No, try understanding the MVC pattern, the idea is that the model is not aware of the view and doesn't have to be. Also you can't call JS with php, which is a server side language and doesn't know anything about the client side scripts.
What you want is to implement long polling. I recommend you to learn and read about the basic technologies involved before trying to implement something.
Upvotes: 1
Reputation: 101
PHP is a server side language. This means the PHP file will get processed on the HTTP server and then deliver the generated HTML page to the client.
Javascript (JS) is interpreted on the the client (browser) and interfaces with the HTML and other remote resources.
Due to this model, PHP and JS know nothing about each other. So to call JS directly from the PHP file is not possible.
If you are looking to make a client browser call a JS function and the PHP script defines the values for the JS function you can use echo() and some string concatenation
//this is an example and will not run.
echo "<script>myJsFunction('" . $arg1 . "','" . $arg2 . "')</script>";
This will embed the JS function call in the HTML page returned to the client. Once the client renders the HTML page it will execute the function call as it comes across it.
If you could give an example of what you trying to do I might be able to give you a more accurate answer.
For a deeper explanation of the client server architecture and where things get executed have a look at Web Browser Client Server Architecture
Upvotes: 2