embedding Javascript in PHP

One of the less known uses of external JavaScript is the ability to reference a PHP file instead of a .js file. This does seem to breach scripting etiquette, as we all "know" that server side and client side scripts are prohibited from interacting. Well, it turns out superficial exchange is allowed. Using external JavaScript, you’ll see how PHP and JavaScript can work together in a way you may not have thought possible, and to the great benefit of JavaScript.

The syntax to referencing a PHP file using external JavaScript is consistent enough with what we already know:

<script type="text/javascript" src="myscript.php"></script>


where myscript.php is either an absolute or relative path to a PHP script instead of the usual .js file. You can even pass parameters to the PHP script through the URL string:

<script type="text/javascript" src="myscript.php?param1=bob&param2=thomas"></script>

Your PHP script can then get to these parameters using the global variable $HTTP_GET_VARS[]. So you’re probably wondering at this point: "So what’s the catch?" Well, there is no catch really, just a few limitations. Since we are invoking the PHP script indirectly and via JavaScript, the final output of the PHP script needs to be valid JavaScript. Think of it as a dynamic .js file, bounded by the same limitations as a regular .js file. A normal PHP script called inside a PHP page can output raw HTML and modify the source code of the page. The JavaScript invoked version obviously cannot, but don’t worry, there’s plenty of what it can do.

Here’s a basic example of a PHP script- ip.php – being called by external JavaScript to do something that JavaScript alone cannot:

 

<?

//"ip.php" example- display user IP address on any page

Header("content-type: application/x-javascript");

$serverIP=$_SERVER['REMOTE_ADDR'];

echo "document.write(\"Your IP address is: " . $serverIP . "\")";

?>


And once called by external JavaScript:

<script type="text/javascript" src="ip.php"></script>

Output: Your IP address is: 192.168.18.1

In the above, we have a normal PHP script that writes out the IP address of the visitor when referenced using external JavaScript, with two important details:

  • A JavaScript header is sent at the very beginning to inform the page that our PHP script is outputting a JavaScript file.
  • Since the final output of our PHP script needs to be a valid .js file, whatever the PHP outputs must conform to valid JavaScript syntax. So to display the IP address from the perspective of JavaScript, the echo function above includes document.write() as part the content to send back to the page.

Notice how I didn’t output the JavaScript script tag itself <script></script>), as just like inside a regular .js file, this isn’t required nor valid.

The ability to reference a PHP script inside your external JavaScript can be very useful! It means your JavaScript now has access to once exclusive information on the server side, whether it’s the server time, the visitor’s IP address, a list of all the files within a certain directory, or mySQL database information. Now even regular HTML pages can utilize this dynamic information, as all they need is a JavaScript on the pages that in turn references the desired PHP script on your server or elsewhere.

Enjoy 😉

Advertisements

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

4 Responses to embedding Javascript in PHP

  1. Pingback: Tweets that mention embedding Javascript in PHP « whileloop -- Topsy.com

  2. John Schmdidt says:

    Not a comment, but a question.

    I’m beginner with PHP. I run following statement:

    echo “\n”;

    JS is a sibling directory of the PHP source file’s location. Thus I’m moving one directory up and then back down to the sibling. Since some weeks ago this doesn’t work any more, only a javascript in the same directory is found.

    I run it on Win7, test browsers are IE9 and FF4. It seems that relative paths don’t work any more. What may cause this?

    Thanks a lot!

    Kind regards,
    John

    • Cameron says:

      Hi John
      I don’t quite get your problem.

      If you are running the statement echo “\n”;, this will just create a new line in your HTML script, but nothing on your “screen”.

      For your issue with relative URLs, it is hard to trouble-shoot without knowing your whole system set-up, but you could try having your PHP script refine the relative URL to an absolute URL (example here). Also, bear in mind that the relative URL is relative to where the page is served from, not to the individual PHP script location; ie, if you are calling a script from http://yoursite.com/php/script.php for a page being served at http://yoursite.com/indexthen the relative URL should be ./js/script.js (NOT ../js/script.js). Note the single “.” denoting current directory.

      I hope that helps.

  3. John Schmidt says:

    Sorry, I have made a tipo in my name email! -> John Schmidt and schmidtjohn@yahoo.com are correct.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: