views:

77

answers:

2

(Rhetorical Question)

I ran into a bizarre scenario today where I wanted PHP to update how the javascript behaved on-the-fly. It was irritating, here is what I tried...

/*
 * ajax-php-javascript-function-loader.php
 *
 * this gets called by AJAX and defines or re-defines the 
 * definition of dynamicDoStuff()
 */
 <script type="text/javascript">
     function dynamicDoStuff(a,b){
          <?php
          //dynamically defined function behavior
          ?>
     }
 </script>

This did not work because when the new javascript was loaded, it's scope of the new function definition was limited to the new script tags. Scripts elsewhere on the page couldn't read it.

So here is what you have to do.

/*
 * index.html
 */
 <html>
     <head>
        <script type="text/javascript">
           var dynamicDoStuff;
        </script>
        <!-- Other Head Stuff -->
     </head>
     <body>
         <!-- the body of the site -->
     </body>
 </html>

and

/*
 * axax-php-javascript-function-loader.php
 */
 <script type="text/javascript">
     dynamicDoStuff = function(a,b){
         <?php
         //dynamically define function behavior
         ?>
     }
 </script>

by defining the name of the function in the header it becomes globally accessible so you can re-purpose it dynamically using ajax and (php or whatever)

+2  A: 

Instead of just

function newFunctionViaAjax() { ... }

you could instead use

window['newFunctionViaAjax'] = function newFunctionViaAjax() { ... };
Pointy
Very nice. This avoids having to declare the function in advance.
Brooks
A: 

A better approach may be to just have your AJAX method return data, in this case, a flag indicating which behavior your the method in question should adopt.

var ajaxResponseHandler = function(jsonResponse) {
    dynamicDoStuff = jsonResponse.someFlagFromTheServer == someExpectedValue 
         ? staticDoStuffA
         : staticDoStuffB;
};

Ideally, at least in most situations, your AJAX method should just return data anyway.

Also, with this method, you can have the required alternate behavior defined in a normal JavaScript file that is already loaded by the client, instead of mixing JavaScript in with your PHP.

Justin Johnson
Obviously, this is true of most situations. In my case I was loading a Prototype window, the content of which was created by PHP. The behaviors of the elements within the Prototype window are determined by a multitude of factors including the who the user is, what they've done so far, and what they chose to look at. The simplest route was to define the behaviors on-the-fly. I can imagine other situations, especially ones that are dynamic or closed-loop, where this would be useful as well.
Brooks
Also... This design pattern allows a great deal of modularity as functions may be defined ambiguously and customized on-the-fly to fit a given module's agenda (allowing them to loaded and unloaded dynamically).
Brooks