PHP
  Home arrow PHP arrow Page 5 - PHP and JavaScript, Pooling Your Resou...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

PHP and JavaScript, Pooling Your Resources (continued)
By: Brian Vaughn
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 19
    2005-09-27

    Table of Contents:
  • PHP and JavaScript, Pooling Your Resources (continued)
  • Separating the Logic
  • What Does PHP Do?
  • Main Layout
  • Is it PHP? Or Javascript?

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    PHP and JavaScript, Pooling Your Resources (continued) - Is it PHP? Or Javascript?


    (Page 5 of 5 )

    Our external file may have a .php extension, but our index page thinks it’s a JavaScript file. This is made possible through the use of PHP’s ‘header’ function, as previously discussed in part one of this article. By using this function, we’re able to harness the power of PHP along with the power of JavaScript to produce some pretty interesting results. Let’s take a look at our file:

    <?php
          # set appropriate content type - to tell the browser we're
    returning Javascript
          header( 'Content-Type: text/javascript' );
          # establish connection to the MySQL server

          mysql_connect( 'localhost', 'root', '' );
          mysql_select_db( 'devshed' );
    ?>

          // set quick reference to child menu object
          var child_menu_obj      = document.getElementById( 'child' );

          // erase all current (child) SELECT menu options
          while ( 0 < child_menu_obj.options.length )
                child_menu_obj.remove( 0 );     

    // (code generated by PHP loop)
    <?php
          # retrieve Parent ID from URL
          $parent_id  = mysql_escape_string( $_GET['parent_id'] );     

          # run SQL query to return all child menu options
          $db_query   = "SELECT * FROM php_js_child_menu WHERE
    parent_id = $parent_id;";
          $db_result  = mysql_query( $db_query );     

          # outout a SELECT menu option for each row returned
          if ( $db_result ) {
                while ( $l_db_row = mysql_fetch_assoc( $db_result ) )
    {           

                      # show all retrieved (child) SELECT menu
    options
                      $l_child_id = $l_db_row['id'];
                      $l_child_name     = $l_db_row
    ['name'];                 

                      # add new option to child menu
    ?>
                      var option_obj = new Option( '<?php echo
    $l_child_name; ?>', '<?php echo $l_child_id; ?>' );
                      var option_rank =
    child_menu_obj.options.length;
                      child_menu_obj.options[ option_rank ] =
    option_obj;
    <?
                } # END while results
          } # END if results
    ?>
    // erase loading message in parent window
    reset_hint();


    There are a couple of important steps within this file. The first, as previously described, is the use of the ‘header’ function to tell the document that this file is actually a JavaScript file. We’ve already talked about that one, so we’ll skip over it now.

    The second function of this file is to retrieve all ‘child’ menu options for the given ‘parent’ menu option that has been selected. If you remember earlier, when a ‘parent’ menu option is selected, it calls the external PHP file. When it does this, it also passes URL arguments along with the call, namely the primary key of the ‘parent’ menu’s SQL record. Our external file then can retrieve that ID from the URL and use PHP’s native SQL querying functions to retrieve all associated ‘child’ records.

    Once we have done that, our PHP code loops through the resulting records and prints a few lines of JavaScript code for each. Remember that once our file has been rendered by the server, the client’s browser will think it is actually a JavaScript file. Because of that, we can output plain JavaScript code and it will be executed as any other JavaScript code would be.

    Let’s look one more time at the JavaScript code being generated by our PHP file:

    // set quick reference to child menu object
    var child_menu_obj      = document.getElementById( 'child' );

    // erase all current (child) SELECT menu options
    while ( 0 < child_menu_obj.options.length )
         child_menu_obj.remove( 0 );

    // (code generated by PHP loop)
    var option_obj = new Option( 'NAME', 'ID' );
    var option_rank = child_menu_obj.options.length;
    child_menu_obj.options[ option_rank ] = option_obj;

    // erase loading message in parent window
    reset_hint();

    As you can see, the JavaScript is actually very simple. First we retrieve a reference to our child SELECT menu object. Then we erase all options currently found in that menu, to give us a clean slate to work with. Next, our PHP script generates a create statement for each SQL option returned. This code simply creates a new SELECT menu option by passing it a name and a value. In this case, we’ve chosen the record’s primary key as the value to be processed when a user submits our form. Lastly, we call the ‘reset_hint’ function, to erase the “Retrieving list values” message.


    What Have We Learned?

    Our sample application is now complete, and I encourage you to try it out for yourself to get a better feel for just how powerful the techniques we’ve discussed can be. It doesn’t take much imagination to realize how this type of approach can easily be used to clean up existing user interfaces, and make them more user-friendly.

    The code we have developed for this application is also pretty browser-friendly, having been tested in Mozilla Firefox 1.0, Netscape 7.2, and IE 6.0. (It is worth mentioning that our application will not run properly in Opera, as of version 7.23.)

    If you would like to view a completed version of the application, please visit the following URL:

    http://portfolio.boynamedbri.com/devshed/php_and_js/

    If you would like to download the source code, you may do so here:

    http://portfolio.boynamedbri.com/devshed/php_and_js/php_and_js.source.zip

    That’s it for now. Thanks for reading, and hopefully I’ll see you soon!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · The app works great, except that the hint box doesn't update dynamically in IE6, but...
       · Glad to hear it :)
       · I have a PHP page, which references a 'javascript/PHP' file. (The file uses PHP to...
       · This scripts work with Opera8.5Very nice. It will help me a lot.
       · you should be able to include the file either way, but I normally use the "<script...
       · thank you :) i'm glad to hear it!
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT