HomePHP Page 3 - PHP and JavaScript, Pooling Your Resources
You Want More JavaScript? - PHP
As a web programmer, a wide variety of scripting languages are available for you to use. Each language has limitations, but by using more than one in conjunction many of those limitations may be overcome. This article will discuss the benefits of using two such languages, PHP and JavaScript, as well as provide source code for creating a basic demo application.
So far we’ve talked about how to generate JavaScript using PHP, and how that Javascript can then interact with users on a real-time basis. However, our initial problem still remains: once our page has been rendered, our PHP code ceases to be –- leaving the management of both data and user interaction to JavaScript. Although Javascript offers many powerful features, relying on it solely from this point on may still be unnecessarily restricting.
“What if we could allow JavaScript to call back to PHP whenever it wanted help?” you may be wondering. The answer is that we can. Using three simple lines of JavaScript code, we can dynamically add as many Javascript/PHP files as we want to a page, and in real time. This opens up the doors for an enormous number of user-friendly features that would not otherwise be possible. We’ll take a look into a few of those features shortly, but for now let’s look at how this can be accomplished. Consider the function below:
function attach_file( p_script_url ) { // create new script element, set its relative URL, and load it script = document.createElement( 'script' ); script.src = p_script_url; document.getElementsByTagName( 'head' )[0].appendChild( script ); }
The above function takes as a parameter a relative URL to an external file. (This file may be a plain JavaScript file, but it may also be a PHP file disguised as a JavaScript file, as previous discussed.) The URL is used to create a new script object, which is then attached to the current document’s <head> tag. In other words, this function will retrieve and attach an external JavaScript or PHP file to a page after the page has already been loaded.