Home arrow PHP arrow Page 3 - PHP and JavaScript Interaction: Storing Data in the Client, part 1

Building JavaScript Arrays with PHP: the "createJavascript()" function - PHP

Modern websites demand heavy interaction between server-side and client-side programming. In the first part of this article series, we will implement a simple mechanism to make PHP and JavaScript interact, creating a function which can build an array structure and store information in it. It will allow for programmatic data manipulation without server interaction.

TABLE OF CONTENTS:
  1. PHP and JavaScript Interaction: Storing Data in the Client, part 1
  2. Lord of the Arrays
  3. Building JavaScript Arrays with PHP: the "createJavascript()" function
  4. Dealing with result sets
  5. Getting practical: putting the "createJavaScript()" function into action
By: Alejandro Gervasio
Rating: starstarstarstarstar / 55
May 04, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

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: