Home arrow PHP arrow Page 5 - PHP and JavaScript, Pooling Your Resources (continued)

Is it PHP? Or Javascript? - PHP

In this article, you will learn how to combine PHP and JavaScript to create two SELECT menus, one containing categories, and the other containing only those options applicable to the category selected.

TABLE OF CONTENTS:
  1. PHP and JavaScript, Pooling Your Resources (continued)
  2. Separating the Logic
  3. What Does PHP Do?
  4. Main Layout
  5. Is it PHP? Or Javascript?
By: Brian Vaughn
Rating: starstarstarstarstar / 22
September 27, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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!



 
 
>>> More PHP Articles          >>> More By Brian Vaughn
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: