Execute javascript function from a PHP function

By : Greg
Source: Stackoverflow.com

I'm trying to find the best and cleaner way to execute a javascript function if a PHP session exists.


  • contains javascript function -> function doStuff(){ //do stuff }


  • contains js file -> in head
  • contains PHP class that check for $_SESSION -> included before DOCTYPE

Please let me know thougts (I'm using PHP, javascript, jQuery).

  1. Best way to execute js script if $_SESSION exist?
  2. Best way to stop js script if $_SESSION is destroyed?



By : Greg

Can't cross the server/client boundary, so best-case is to dump something on the page that queues the client to fire the javascript function.

Alternatively, you could have something like session_verify.php that you can reference in an AJAX call, then "continue executing"/"stop" based on the response you receive back.

Pseduo code:

if (ajax_response_from_session_verify() == still_logged_in){
  execute doSomething();
  stop doSomething();

Keep in mind though, that calls to the session check file could potentially prolong the session depending how you're using it. (I'm not sure if that's desired)

You have two options.

  1. Have the function in a separate is file and include it only if the session is set.
  2. Serve the JS file as a PHP file. This will allow you to run PHP commands in your JS file. Just make sure your content type is ok.
By : JohnP

then, in your HTML head:

<script type="text/javascript">
document.ready(function() {
<?php echo $script; ?>

This video can help you solving your question :)
By: admin