PHP
  Home arrow PHP arrow Page 3 - PHP and JavaScript Interaction: Storing Data in the Client, part 1
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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 Interaction: Storing Data in the Client, part 1
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 46
    2005-05-04


    Table of Contents:
  • PHP and JavaScript Interaction: Storing Data in the Client, part 1
  • Lord of the Arrays
  • Building JavaScript Arrays with PHP: the "createJavascript()" function
  • Dealing with result sets
  • Getting practical: putting the "createJavaScript()" function into action

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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 Interaction: Storing Data in the Client, part 1 - Building JavaScript Arrays with PHP: the "createJavascript()" function
    ( Page 3 of 5 )

    In a moment of inspiration, I named the function "createJavaScript()". Let's see how it works. First, the function accepts two incoming parameters. It takes a generic $dataSource argument, which, as the name suggests, represents the source of data to be populated in the JavaScript arrays. Since the function must be flexible enough, I decided that it will accept either a flat text file or a database result set as possible data sources.

    The second parameter is the name of the JavaScript array to be generated. So, if we ever need a JavaScript array named "news," which stores news headlines from a flat file called "news.dat," our function might be defined basically as following:

    function createJavaScript($dataSource,$variableName){
      // function code goes here
    }

    And, at any time, it may be invoked as shown below:

    createJavaScript('news.dat','news');

    Having explained the meaning of each incoming parameter, it's time to list the code for the function. Here is its definition:

    function createJavaScript($dataSource,$arrayName='rows'){
      // validate variable name
      if(!is_string($arrayName)){
        die('Invalid variable name');
      }

    // initialize JavaScript string
      $javascript='<script>var '.$arrayName.'=[];';

    // check if $dataSource is a file or a result set
      if(is_file($dataSource)){
       
        // read data from file
        $row=file($dataSource);

        // build JavaScript array
        for($i=0;$i<count($row);$i++){
          $javascript.=$arrayName.'['.$i.']="'.trim($row[$i]).'";';
        }
      }

      // read data from result set
      else{

        // check if we have a valid result set
        if(!$numRows=mysql_num_rows($dataSource)){
          die('Invalid result set parameter');
        }
        for($i=0;$i<$numRows;$i++){
          // build JavaScript array from result set
          $javascript.=$arrayName.'['.$i.']="';
          $tempOutput='';
          foreach($row=mysql_fetch_array($dataSource,MYSQL_ASSOC) as $column){
            $tempOutput.=$column.' ';
          }
          $javascript.=trim($tempOutput).'";';
        }
      }
      $javascript.='</script>'."\n";

      // return JavaScript code
      return $javascript;
    }

    The function code is really easy to follow, so take it slowly while you look at what it does. As I mentioned previously, the function accepts the two parameters $dataSource and $arrayName, respectively. Please notice that I've specified a default "rows" array name for the last parameter, which, as usual, might be easily changed to generate another JavaScript array.

    The first step to be followed is to check whether the name of the array passed as the argument is a string type data. If it's a string, then a $javascript variable is set, assigning to it the initial code for building the <script> opening tag, and initializing the proper JavaScript array. Otherwise, the function is simply killed, by calling a regular die() statement.

    The following lines execute the process above described:

    // validate array name
    if(!is_string($arrayName)){
      die('Invalid variable name');
    }

    // initialize JavaScript string
    $javascript='<script>var '.$arrayName.'=[];';

    The next task to be performed within the function is verifying whether the supplied argument $dataSource is either a text file or a database result set. Using the "is_file()" PHP built-in function, the checking process is quickly done.

    If the function determines that the argument passed as a data source is a file, then each line of the corresponding file is read and stored in the dynamically generated JavaScript array, whose name was specified as a function argument. How is this done? Just by looping through the file lines and assigning their possible values to the JavaScript array, in the following way:

    // read data from file
    $row=file($dataSource);
    // build JavaScript array
    for($i=0;$i<count($row);$i++){
      $javascript.=$arrayName.'['.$i.']="'.trim($row[$i]).'";';
      }
    }

    Now, the function pieces are fitting nicely, because at this point the JavaScript array has been dynamically generated, storing the contents of the source file specified. Now, the data resides in the memory of the client's computer, waiting to be processed in any way possible. Probably, you'll have your own ideas about how to take advantage of such a useful data structure.

    But, wait a minute! What hapens if we've passed a result set to the function? Don't worry. We'll cover that in the next section. Keep on reading!



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT