Pass filenames by to my javascript files

I need to pass by a filename and location (send_message.php) from my wordpress plugin to a javascript file, so that I can use send_message.php with ajax in my js.

Now first thing I thought is to just echo the name in a hidden div or set it as an attribute of some tag and then readout that value with js. but that doesn’t seem good practise.

Read More

in IRC they told my to echo a <script type='application/javascript'> var filename = <?php echo plugins_url(...) ?>, but that doesn’t work because I can’t access the variable too, and form my feeling thats also not very nice practise.

another idea was to make a *.php file with header('Content-Type: text/javascript') and then setting the variable there with var filename = <?php.... That seems like a nice way for my (if using php files as javascript is ok? :P). but it doesn’t work because wordpress tells me that plugins_url() is not defined when I call it from that file somehow?

Is that a good way or is there maybe a better? (And if it is a good way, how do I use plugins_url inside my iAmJS.php file)

Related posts

Leave a Reply

2 comments

  1. var filename = <?php echo plugins_url(...) ?>
    

    This isn’t working because plugins_url probably contains a string. Add quotes around it so JavaScript will treat it as a string:

    var filename = '<?php echo plugins_url(...) ?>';
    
  2. you can sniff it out in JS from an external file:

    (function(){ // script filename setter, leaves window.__filename set with active script URL.
    if(self.attachEvent){
     function fn(e,u){self.__filename=u;}
     attachEvent("onerror",fn);
     setTimeout(function(){detachEvent("onerror", fn)},20);
     eval("gehjkrgh3489c()");
    }else{
     Object.defineProperty( window, "__filename", { configurable: true, get:function __filename(){
       try{document.s0m3741ng()}catch(y){
        return "http://" + 
         String(y.fileName || y.file || y.stack || y + '')
         .split(/:d+:d+/)[0].split("http://")[1];
        } 
     }})//end __filename
    }//end if old IE?
    }());
    
    
    //demo:
    alert(__filename);
    

    a bit ugly i admit, but it works, even in IE…

    if you don’t care about IE, it can be much shorter:

    Object.defineProperty( window, "__filename", { configurable: true, get:function __filename(){
       try{document.s0m3741ng()}catch(y){
        return "http://" + 
         String(y.fileName || y.file || y.stack || y + '')
         .split(/:d+:d+/)[0].split("http://")[1];
        } 
    }})//end __filename