PHP
  Home arrow PHP arrow Page 3 - PHP and JavaScript Interaction: Storin...
Dev Shed Forums 
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 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
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: 4 stars4 stars4 stars4 stars4 stars / 39
    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:
      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 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


       · The article shows a simple and effective way to create and populate a JavaScript...
       · The article is very understanding. I hope the 2nd part is coming soon, because I do...
       · Hi friend,This first part implements a JavaScript array built with server-side...
       · Hi...This article is really very nice. It's also written in simple to understand...
       · Hi Sukhi,Thanks a lot for the compliments about my PHP-JavaScript related...
     

       

    PHP ARTICLES

    - Validating Web Forms with the Code Igniter P...
    - Output Buffering
    - Paginating Database Records with the Code Ig...
    - HTTP Headers in Web Development
    - Project Management: Administration
    - Building a Database-Driven Application with ...
    - User Authentication for a Project Management...
    - Introduction to the CodeIgniter PHP Framework
    - Adding Users for a Project Management Applic...
    - Migrating Class Code for a MIME Email to PHP...
    - Login and Logout Authentication for a Projec...
    - Composing Messages in HTML for MIME Email wi...
    - Project Management: Authentication
    - A Better Way to Determine MIME Types for MIM...
    - Project Management Overview





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway