PHP and JavaScript, Pooling Your Resources

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.

Combining Scripting Languages

PHP is a server-side scripting language, processed remotely before a page is rendered. As such, it has very limited access to client-side objects, and no real way of interacting with the client on its own once a page has been loaded. However, it has numerous strengths that make it a very practical and easily maintained choice for most of today’s dynamic website projects.

JavaScript is a client-side language capable of interacting with the user in real time, even after a page has been rendered. Through the use of event handlers, Javascript may respond to a user’s button click, key stroke, menu selection, and so forth. Javascript is widely supported and continues to grow with each new release.

By combining these two languages, many interesting things may be achieved. Perhaps one of the most common implementations is to dynamically generate and pre-populate a form using PHP, then validate the form’s various fields in real time through the use of JavaScript. For instance, this allows PHP to specify a field as being required and then rely on Javascript to enforce that requirement. This example is a rather simple one, but it is very useful.

Most PHP and JavaScript combinations follow the basic forumla outlined below:

Step 1: PHP functions retrieve and manipulate the data.

Step 2: JavaScript functions validate user input and/or provide the user with helpful information.

Although very useful, one drawback to the above process is the inability for PHP to further interact with the data in real time based on the user’s actions. In other words, JavaScript may respond to user input, but once the page has been rendered PHP cannot assist in manipulating or retrieving any additional information. This limitation lessons the user-friendliness of a system by requiring JavaScript to load or reload a page each time it needs PHP to process or generate information.

In this article we will discuss an easily implemented way of getting around this problem by dynamically attaching PHP files to a page with the help of JavaScript. This will allow us to process information in real-time using not only JavaScript but PHP as well. Part 1 will discuss the basics, with a primary focus on attaching the external PHP files in a simple, example application. Part 2 will then expand our basic application and introduce a few additional concepts. By the end of the tutorial, you should have a firm understanding of how to effectively combine PHP and JavaScript in order to achieve a wide range of creative and unique results.

{mospagebreak title=PHP Disguised as JavaScript?}

One very useful feature of PHP is that it allows you to set header information for the document you are generating. This header information can control a wide variety of things – forcing the user’s browser to open the file in a certain application, or to redirect the user to another page, or to authenticate the user before proceeding, and so on.

By default, PHP files are treated as an HTML file by a user’s browser, since the output rendered by the server is generally text or HTML. The default content type then for an HTML (or PHP) file is “text/html.” When a browser encounters this content type, it opens the file itself and renders any HTML markup found within the file appropriately. This is good, as the primary purpose of an HTML page is to format and display information.

A JavaScript file (“text/javascript”), however, is different. It will be rendered in plain text, as its primary purpose is not to display information, but to manage it through the use of statements and functions. Put another way, placing HTML markup in a JavaScript file will result in Javascript errors, not an HTML page. Likewise putting JavaScript in an HTML file (without the appropriate encapsulating tags) will also cause undesirable results in most cases.

So how do we avoid this problem? The answer is simple: by telling our header functions to set the appropriate content type, we are able to tell the browser to treat a PHP file not as a “text/html” file but as a “text/javascript” file. To do this we simply place the following code at the top of our file:

header( ‘Content-Type: text/javascript’ );

Note: It is important to place the header() function call at the top of our PHP file. Placing it lower may result in compilation errors, as all header information must be sent before any other content is output.

The implications of what we have just discussed may already be clear to you, but in case they are not, let us consider the benefits of generating a JavaScript file with PHP. JavaScript files control various aspects of the user’s browser and its display, ranging from simple elements of style and formatting to more complex validation and HTML generation. However, JavaScript is still generally written in a static nature –- that is, the code itself doesn’t change, only the data it is manipulating.

In many cases where PHP is used to dynamically generate a page and its various HTML objects, this may be limiting. Our JavaScript code may need to know about every object in order to intelligently manage a single object. We can accomplish this goal by using the header tag mentioned above. PHP can now generate not only our HTML, but all associated Javascript code as well — resulting in yet another level of complexity in our dynamic system.

{mospagebreak title=You Want More JavaScript?}

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.

Let’s look at an example.

{mospagebreak title=How Does This Work?}

For our first application, we’ll keep things simple. The primary focus here is to demonstrate how our two languages interact. To do that, we will construct two files: the first a simple PHP page that comprises mainly HTML, and the second a PHP page that generates JavaScript. Our first page will be as follows:

      # start the session, and clear any existing values
      $_SESSION[‘js_count’]   = 0;
<!– main HTML display –>
            <title>PHP & Javascript – Example</title>
            <STYLE type=’text/css’>
                  /* set Body display properties to make things pretty */
                  body, p, th, td {
                        font-family: Tahoma, Arial, Helvetica, sans-serif;
                        font-size: 11px;
            <SCRIPT type=”text/javascript”>    
                  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 );

            <!– call external PHP / Javascript file when clicked –>
            <a href=”javascript:attach_file( ‘javascript.php’ )”>What time is it?</a>
            <span id=”dynamic_span” />

As you can see, things are pretty simple at this point. The PHP file initiates a SESSION variable, ‘js_count’ to be 0 and then outputs a simple HTML page. The only JavaScript present so far is the function we discussed earlier. An anchor tag is displayed to allow the user to call that function. A ‘dynamic_span’ tag is also present, and we’ll see why shortly. Now let’s take a look at our other PHP/JavaScript file, named ‘javascript.php’:

            # set appropriate content type – to tell the browser we’re returning Javascript
            header( ‘Content-Type: text/javascript’ );         

            # start the session

            # determine the current time
            $time                = date( ‘g:i a’ );           

            # determine how many times the user has called the function, then increment it
            $js_count          = ( ++$_SESSION[‘js_count’] );           

            # based on the count, set the appropriate display value
            if ( $js_count == 1 ) {
                        $inner_html       = “This is your first time asking. It is $time.”;
            } else if ( $js_count <= 3 ) {
                        $inner_html       = “You have asked me $js_count times now. It is $time.”;
            } else {
                        $inner_html       = “You have already asked me $js_count times. Shut up!”;
            } # END big-nasty-else-if-block
// retrieve span object, and attach additional HTML to it
dynamic_span_obj          = document.getElementById( ‘dynamic_span’ );
dynamic_span_obj.innerHTML     += ‘<?php echo $inner_html; ?> <br>’;

Once again this file is pretty simple. Our PHP code simply tells the browser that it is a JavaScript file, then it retrieves the ‘js_count’ SESSION variable and creates a return String value depending on how many times the file has been called. Underneath our main PHP, our JavaScript simply updates the ‘dyamic_span’ tag on the main page, appending the PHP-generated String value.

That’s it?

That’s it. Try it out! So far we’ve kept things very simple, but hopefully you are beginning to see the possibilities that this type of interaction between PHP and JavaScript allows for. Part 2 of this article will then continue by expanding our example application to include some additional, user-friendly features as well as to implement a more practical scenario with PHP pulling its information from a MySQL database.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye