Sie sind auf Seite 1von 6

PHP and JavaScript Interaction: Storing Data in the Client, part 1 (Page 1 of 5 ) Introduction Certainly the concepts have

been covered repeatedly in countless articles, books or papers you can imagine, digging into the territory of Web development: server-side and client-side programming. While nowadays these areas are clearly differentiated and stand on their own in distinct scenarios, the requirements of modern websites demand heavy interaction between them. From database-generated navigational menus, to server-based CSS style manipulation, examples of server-client programming interaction are truly vast and numerous. In most situations, this interaction is bi-directional. You might see either server-side languages, such as PHP, generating client-code, that means JavaScript/(X)HTML, or JavaScript functions building up data to be processed in the server. Either way, the process is often a two-way street. Particularly, if we take into consideration the first half of the equation, where PHP (or the server-side language of your choice) performs some kind of quick client-program generation, we rapidly end up storing some temporary data directly in the client computer's memory. Of course, here we're discarding any other well-known client-side storage process, such as cookies, imagebased data tracking, data coming in from local cached files or even from XML files. This issue immediately brings to mind a question that has caused several heated discussions: is it good to store data in the client this way? The range of opinions varies widely from a rough complaint to a resounding yes. The truth is that the answer is hard to give, since it relies strongly on several factors, such as amount of data, type, user hardware (remember we're using client system resources) and particularly data relevance. Definitely, we'll agree that no critical data will be stored in the client, even if this sounds like common sense stuff. If you ever thought that critical information should be stored in the user's environment, please change your mind right now! However, regarding my personal experience, when building applications that heavily eat up a client's computer resources, difficulties can easily appear, causing browser crashes or complete system hangs. But, all is not lost. As hardware rapidly evolves, and it's widely available to average users, there are certain cases where it is possible and even desirable to have a small application directly using the client's memory to store temporary data. That's where this article series comes in. We'll demonstrate how to use this approach to store data in the client and noticeably reduce the client-server transferring process, developing a couple of applications useful for implementation on any project of your choice. Let's get ready to try out a combination of PHP and JavaScript. PHP and JavaScript Interaction: Storing Data in the Client, part 1 - Lord of the Arrays (Page 2 of 5 ) Historically, one of the most common methods employed by developers to store data in the client for faster processing, is the use of JavaScript arrays. This aproach has been used for years in diverse aplications, where PHP generates the necessary code to create a JavaScript array structure and stores data either from files or, more infrequently, from database records. Let's consider, for instance, the following example, which shows a rough approximation to populate a JavaScript array with database information: <script> var rows=[]; <?php $db=mysql_connect('dbhost','username','password') or die('Error connecting to the server'); mysql_select_db('mydatabase') or die('Error selecting database'); $result=mysql_query('SELECT * FROM mytable') or die ('Error performing query'); while($row=mysql_fetch_array($result, MYSQL_ASSOC)){ ?>

rows[rows.length]=<?php echo '"'.$row['name'].'"'?>; <?php } ?> </script> In the above example, we're declaring a JavaScript "rows" array. We then use interspersed, procedural PHP code to connect to the MySQL server, extract some records from a sample table, and finally store the contents of a hypothetical "name" table field in the array. Despite the fact that the aproach is quick and dirty, it shows in a nutshell that storing server data using a PHP - JavaScript interaction is really simple. Before I hear the loud and well-intended complaints resounding in my ears, let me say that there are serious drawbacks with this technique. First, we're mixing up PHP code with JavaScript, which may lead to undesirable bad coding habits. The second pitfall is rather obvious: what if our harmless, simple database table contains thousands of records to be displayed? Well, there may be a few upset visitors out there, watching their browsers crash. That's definitely not a very good situation! However, the topic is not as unfavorable as it seems. There are cases where we can take advantage of JavaScript arrays to build up a less demanding application, which hopefully will run smoothly in the client's computer, avoiding unnecessary requests to the server. That sounds fairly good, doesn't it? But before working directly with arrays, we need to address a key issue. Since we don't want to mess up our code by mixing PHP and JavaScript, we're going to keep them in separate layers, creating a PHP function that will take care of generating the corresponding JavaScript arrays, but maintaining the rest of the code pretty untouched. Also, this introduces an extra benefit. Having a generic function that creates JavaScript code and returns the proper arrays is quite portable for use in applications with this kind of client requirement. The subject is really promising. So, let's start defining the PHP function to generate the JavaScript arrays. 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! PHP and JavaScript Interaction: Storing Data in the Client, part 1 - Dealing with result sets (Page 4 of 5 ) By now, we're halfway home. We've already seen how to build a JavaScript array from data files, right? Now, the function should be capable of working with database result sets, at least at a basic level. Fortunately, our function checks to see what type of data source has been provided. If the parameter $dataSource is a result set, then table records are extracted with a regular loop, and stored in the proper JavaScript array, following the same method aplicable in flat data files. The lines that extract table records and create the JavaScript array are listed below: // 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).'";'; } Luckily, we've stored database records in the dynamic array. Before we move on, a little explanation is in order here. Notice that inside the loop process we've retrieved each table field, separating them with a single blank space. Why did we do it that way? The reason is quite simple: by doing so, we can access each table field value later, by simply splitting the string of data returned by the function. However, possible additions are probably valid too. We could have stored field values in a bi-dimensional JavaScript array, for further access. The flip side is that we'd be taking up even more client memory, making the overall storage a crash prone process. So, to keep things simple, we're using the first aproach. Still following the function explanation? Good, because we're almost done. Once the function has done its thing building the JavaScript array and populating it either with flat data files or database records, it must end up completing the code, adding a </script> closing tag, and returning the output, just like this:

$javascript.='</script>'."\n"; // return JavaScript code return $javascript; As I told you before, we're almost done. Our function takes a file or database result set, generates an array structure with the values obtained, and finally returns the complete JavaScript code, ready to be included in any application for further processing. Okay, it's time to test our function. Let's show a practical example to see how it can be used. PHP and JavaScript Interaction: Storing Data in the Client, part 1 - Getting practical: putting the "createJavaScript()" function into action (Page 5 of 5 ) In order to see the practical uses of our newly developed function, let's create an example to illustrate its functionality. Say we need to read information from a simple text file that contains some information about music albums, and store that data in a JavaScript array, which will be processed at later time. Our "album.dat" file might look as simple as this: Tales of Mystery and Imagination The Best of The Alan Parsons Project I Robot Eye In The Sky The Turn of a Friendly Card Stereotomy The Definitive Collection Vulture Culture The Instrumental Works Pop Classics Now, we can call our function in the following way: echo createJavaScript('album.dat','album'); That's really simple, right? In this example, we've invoked the function to read data from our "album.dat" file, specifying that the information has to be stored in a JavaScript array named "album." So, what's the point of that? Well, if we take a look at the document source code, we find that the function has nicely created the array structure, storing each file line as array elements, as listed below: <script> var album=[]; album[0]="Tales of Mystery and Imagination"; album[1]="The Best of The Alan Parsons Project"; album[2]="I Robot"; album[3]="Eye In The Sky"; album[4]="The Turn of a Friendly Card"; album[5]="Stereotomy"; album[6]="The Definitive Collection"; album[7]="Vulture Culture"; album[8]="The Instrumental Works"; album[9]="Pop Classics"; </script> I think that you understand now the capabilities of the function. With a few lines of code, the data is now available to us in a JavaScript array. Undoubtedly, we're really storing data in the client. Let's think about its possible uses and build an application to manipulate this data, without loading the server with unnecessary requests. Summary

In this first part of this series, we've implemented a simple mechanism to make PHP and JavaScript interact, creating a function which, once fed with a data source (i.e. files of database records), builds an array structure and stores the information in it. This allows for programmatic data manipulation without server interaction. However, we must be fair about this method and show its pitfalls too. The major issue is, definitely, its strong dependence on JavaScript. The second problem is the limited amount of stored data allowable in the client's machine, without compromising the system's stability. However, despite its weaknesses, the method is still viable for small applications, possibly in intranet environments, where we work with controllable client factors such as scripting enabled or specific hardware requirements. But there are a couple of uses to be reviewed yet. In the second part of this tutorial, we'll use our recently developed PHP function to build a file-based JavaScript ticker, in order to show a real application. In the meantime, take your time and have some fun playing with the code. See you in the next part!

Das könnte Ihnen auch gefallen