Execute javascript function from a PHP function

By : Greg
Source: Stackoverflow.com
Question!

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

js-script.js

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

index.php

  • 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?

Thanks,

Greg

By : Greg


Answers
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();
else
  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:

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


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