Results 1 to 6 of 6

Thread: Can php be used inside javascrpt?

  1. #1
    Join Date
    Sep 2007
    Location
    Maui
    Posts
    602
    Thanks
    266
    Thanked 13 Times in 13 Posts

    Default Can php be used inside javascrpt?

    Is it possible to insert a bit of php inside a javascript? For example:

    Code:
    <script type="text/javascript">
    
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', '<?php echo $ga;?>']);
      _gaq.push(['_trackPageview']);
    
      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
    
    </script>
    Thanks.

  2. #2
    Join Date
    Jul 2008
    Location
    Derbyshire, UK
    Posts
    2,027
    Thanks
    16
    Thanked 315 Times in 313 Posts
    Blog Entries
    13

    Default

    Yes, if the JavaScript is in your web page
    Focus on Function Web Design | Latest News RSS | Facebook | Twitter |
    Fast Edit (A flat file, PHP web page editor & CMS. Small, FREE, no database!) | Fast Edit BE (Snippet Manager) (Web content editor for multiple editable regions!) | Fast Apps |
    The only limit to creativity is imagination: JemCon.org

  3. #3
    Join Date
    Sep 2007
    Location
    Maui
    Posts
    602
    Thanks
    266
    Thanked 13 Times in 13 Posts

    Default

    Thanks. So my example would work as written?

  4. #4
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    To expand on what Beverley said, yes, as long as it's within a page that is processed by PHP. An external .js file usually isn't, although (in some complex ways) it is possible to circumvent that, either by a server setting or by using a .php file as an external Javascript file (with the right headers).

    Usually I just put it in the head section of my page, even if everything else is external-- it's usually just a variable or two that I am pre-setting, so that's fine.


    On the other hand, the order of operations is crucial!

    PHP executes on the server, then everything (after the PHP is done) is sent as plain HTML (+JS/CSS) to the user. Only after that does any CSS or Javascript execute.

    Therefore, there are two scenarios:

    1. You want to have dynamic Javascript, either by having some value retrieved by PHP and inserted into the Javascript or by modifying the Javascript itself (eg, "do I want this script or this one?"). All of that is fine, as long as you do this before any of the Javascript is processed. Once the page loads, it will be static, no longer referring to PHP any more, but just to whatever the [original] output of the PHP was, when it was originally processed.
    You can write Javascript (or part of Javascript) with PHP just like you write HTML with PHP. Same with CSS.

    2. You need to use Javascript to run PHP code in real time. Perhaps you want Javascript to check right now, what time is it on the server?. This must run with Javascript, while the page is already loaded. Technically, this is impossible. You cannot run PHP, a serverside language, with Javascript, after the page has been processed. The only possibility is reloading the page and getting a new value from PHP and going from there.
    However, there is a workaround: Ajax. Ajax allows you to use Javascript to send a new request to the server, but instead of loading a whole new page, you just get some data back (probably as a short string of text, perhaps some HTML elements) and then can manipulate that using Javascript. This requires creating a new, secondary PHP script that does only that section (rather than generating the whole page!). [NB: you can create this then use an include() to include that into the original full PHP, rather than having two unrelated independent copies of the same procedure.]
    Ajax is somewhat complicated to use, varies by browser (at least the older ones), and is subject to security restrictions (primarily the 'only from the same server/domain' requirement).



    So, in short, yes, you can. But the details matter.


    The code you posted above will do exactly this:
    1. PHP will retrieve whatever $ga is.
    2. PHP will output that into the Javascript.
    3. PHP will then serve the entire page to the browser.
    4. The Javascript will operate as if that were a static value [except that it would possibly change every time you reload the page].

    What you did there will not work at all for the purpose of "Javascript asking PHP for a value". Rather, it only works for "PHP [originally] telling Javascript something."
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  5. #5
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,136
    Thanks
    44
    Thanked 3,231 Times in 3,192 Posts
    Blog Entries
    12

    Default

    Your example will work as long as $ga is set to something that makes sense to the script. I think that's the only PHP variable you have there. If I missed another one in the javascript code, it must also resolve to something that makes sense to the script. And of course this must be on a page that's processed by the server as PHP, like index.php, contact.php, or about.php, etc., any page with the .php extension.


    Not directly related to your question (I mention this mostly because Daniel brought it up):

    Your javascript is an on page script. So you do not have to worry about an external javascript using PHP. But it's not all that hard to have an external javascript that's also processed as PHP. Simply give it a .php extension and a javascript header*, and it will be. Then you just have to make sure that whatever PHP that it has in there that becomes javascript when interpreted by the server, actually makes sense as javascript.


    *
    PHP Code:
    header("content-type: application/x-javascript"); 
    See:

    http://www.dynamicdrive.com/forums/showthread.php?54416

    for an admittedly complex example of an external javascript that also uses PHP. But the concept of making it use both is simple.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  6. #6
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    John, you're right that it's not that complicated. It's just usually not worth it (when you can easily put it in your page). Additionally, there's a reason to avoid that: you don't want to be dynamically generating your Javascript every time (especially if it's very long). Instead, just getting one value within the main page, and then using an external .JS file for everything else makes sense. But technically, it's possible, and not too hard. You also must, of course, then use a .php Javascript HREF in your HTML reference to it. The only issue might be (third-party) scripts (already) expecting a .js file.

    The other method, of asking your server to treat .js as .php is more complicated and not possible on many shared hosting accounts. It also obviously wastes resources for processing every .js file (most with no effect except increased processing) as PHP. Of course you can specify certain limits (like only in a certain folder, even just a certain file) but that's complicated. You can do this, by the way, using .htaccess (among other methods). It's the same way that you would get a .html page to be processed as PHP, and there's more info/tutorials out there about that.



    On the other hand, regarding formatting, there actually is a more important point (thanks John for mentioning that because I overlooked it earlier):

    Kuau, you already have single quotes around the PHP for where it is to appear. This is important (crucial even). So that's part of it. But the other part is escaping the PHP value for use in Javascript. It may be a non-issue if you know for certain you will only ever have, for example, numerical values. But if you ever have strings, especially user-generated input, you must be careful about two things:
    1) Integrity of the script (if there's an ' in there, it might stop the script from working, at the very least).
    2) XSS attacks-- if a clever user notices this, and can save content directly into where that JS appears, they can design it so that it will do other things with the Javascript code, such as trying to steal personal information, displaying an ad, and so forth.

    The tricky part is that you must escape this with regards to the location in the Javascript, regardless of what the PHP is doing. Here you'd at least escape ' with \', but possibly more. And if the string already contains \', then it would end up with \\', thereby circumventing the escaping. Depending on how it will eventually be displayed (in the HTML?, adding even more complexity/layers to this) a good option is to use HTML entities to store any potentially problematic characters, so you have &quot; for quotes, etc.
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

Similar Threads

  1. Replies: 24
    Last Post: 09-30-2012, 11:34 PM
  2. How to call an SSI inside a SSI?
    By dpsource in forum Other
    Replies: 0
    Last Post: 02-27-2008, 05:42 PM
  3. swf inside swf
    By queerfm in forum Flash
    Replies: 8
    Last Post: 12-09-2007, 12:37 PM
  4. Tab inside a tab
    By monmagallanes in forum Dynamic Drive scripts help
    Replies: 1
    Last Post: 06-08-2007, 08:24 AM
  5. while inside of while
    By pkcidstudio in forum PHP
    Replies: 9
    Last Post: 05-02-2007, 05:49 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •