开发者

Execute javascript function from a PHP function

I'm trying to find the best and cleaner way to exec开发者_运维百科ute 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


<head>
  <? if (session_is_registered('foo')) echo '<script>doStuff();</script>'; ?>
  ...
</head>

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.


if(session is OK) {
    $script = "doStuff();";
}

then, in your HTML head:

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


Brad is correct that you would need to use PHP to output to the page since you can't directly call JS from the server.

An alternative to writing out script tags is to place a flag in your HTML via PHP, then use JavaScript to read that flag. For instance, you are using jQuery, you may do something like this:

<div id="sessionExists><?php if (isset($_SESSION['foo'])) echo 'true';?></div>

And in your jQuery:

var session = ($('#sessionExists').text() === 'true'))? true : false;

Now you have a JS variable that holds a boolean for "sessionExists," which you can query in JS scripts and act accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜