my dog learned polymorphism*
The moose likes PHP and the fly likes Calling Javascript from PHP Code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Languages » PHP
Bookmark "Calling Javascript from PHP Code" Watch "Calling Javascript from PHP Code" New topic

Calling Javascript from PHP Code

Anand Sonus

Joined: May 28, 2013
Posts: 1
I'm in need of piece of code which will call javascript function from PHP code. Here PHP and javascript are different files. Please anyone help me on this.

Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3013

Welcome to JavaRanch
Do you understand that PHP runs in the server and Javascript runs in the client (browser) so "calling JavaScript function from PHP" is meaningless? If you TellTheDetails with what exactly you need to get done, we can probably come up with a better useful suggestion.

Founder of ExamLab and Systemup
See how I can help you to become an awesome programmer
Anna Harris

Joined: Aug 21, 2012
Posts: 13
I always use echo "<script> function(); </script>";
Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3013

Anna Harris wrote:I always use echo "<script> function(); </script>";

It doesn't work in the way you think it does. You don't even need to have an "echo"- just placing <script> function(); </script> outside <?php ?> tags does the same as what with "echo" does. Particularly, it 'prints' that fragment as a text in the HTML content, and your browser interprets the generated HTML and there is a Javascript snippet calling your function - that's now something like calling-JS-from-PHP.

If calling to a Javascript method in a separate file is all what you need, simply 'import' that Javascript file using <script src> in your <head> block, and then you can call its functions anywhere in the body as you always do.
I agree. Here's the link:
subject: Calling Javascript from PHP Code
Similar Threads
jsp and javascript
input/output stream
Calling PHP from Servlet
Send requsts to a php file using AJAX
calling javascript within php