PHP
  Home arrow PHP arrow Page 7 - PHP and JavaScript Interaction: Storing Data in the Client, part 3
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 3
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 14
    2005-05-18


    Table of Contents:
  • PHP and JavaScript Interaction: Storing Data in the Client, part 3
  • Records wanted! Fetching data from tables
  • Defining data containers: the "createDivs()" function
  • Showing database records: the "displayRecords()" function
  • 1 - 2 - 3 Next
  • Building paging links: the sequel
  • Building client-based result sets: making PHP and JavaScript interact

  • 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 3 - Building client-based result sets: making PHP and JavaScript interact
    ( Page 7 of 7 )

    Let's set up a basic example to test our paging system. To keep things simple, we'll assume that we have stored some records in a database table, which contains data about several songs, including song ID, song title and song author. Nothing unexpected. Here's the full example:

    <?php

      // include createJavaScript function
      require_once('createjavascript.php');

      // connect to the MYSQL server , select database and perform query
      $db=mysql_connect('dbhost','user','password') or die('Error connecting to the server'. mysql_error());
      mysql_select_db('database') or die('Error selecting database');
      $result=mysql_query('SELECT * FROM songs') or die('Error performing query');

      // pass result set $result to the function and create a "rows" JavaScript array

      // with table records
      echo createJavaScript($result,'rows');

      // paginate records in the client side
    ?>
    <html>
    <head>
    <title>Paginating Records with JavaScript</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <script language="javascript">
      var recsPage,page,numPages;

      // set number of records per page
      recsPage=4;

      // calculate number of pages
      numPages=Math.round(rows.length/recsPage);

      // define createDivs function
      createDivs=function(){

        // create records containing <div>
        var recsDiv=document.createElement('div');
        recsDiv.id='records';

        // create paging link containing <div>
        var linksDiv=document.createElement('div');
        linksDiv.id='paginglinks';

        // insert <div> elements into document structure
        document.body.appendChild(recsDiv);
        document.body.appendChild(linksDiv);
        }          

        // define displayRecords function
        displayRecords=function(page){
           var recsDiv=document.getElementById('records');
           if(!recsDiv){return;}
           var div=document.createElement('div');
           div.id='records';
           if(!page){page=1;}

           // extract records from rows array
           for(var i=(page-1)*recsPage;i<((page-1)*recsPage)+recsPage;i++){
             if(rows[i]){

               // insert records as paragraph elements 
               var p=document.createElement('p');
               p.appendChild(document.createTextNode(rows[i]));
               div.appendChild(p);
               }
             }

             // replace old records node with new records node
             recsDiv.parentNode.replaceChild(div,recsDiv);
           }

           // define generateLinks function
           generateLinks=function(page){
             var linksDiv=document.getElementById('paginglinks');
             if(!linksDiv){return;}
             var div=document.createElement('div');
             div.id='paginglinks';

             // assignn default value to array pointer
             if(!page){page=1;}

             // create previous link
             if(page>1){
               var a=document.createElement('a');
               a.href='#';
               a.id=parseInt(page)-1;
               a.style.fontFamily='Verdana';
               a.style.fontSize='11px';
               a.style.fontWeight='bold';
               a.appendChild(document.createTextNode('<<Previous'));
               div.appendChild(a);
               a.onclick=function(){

                 // update record list
                 displayRecords(this.id);

                 // update paging links
                 generateLinks(this.id);
               } 
             }

             // create numbered links
             for(var i=1;i<=numPages;i++){
               if(i!=page){

                 // create paging links
                 div.appendChild(document.createTextNode(' '));
                 var a=document.createElement('a');

                 // assign paging links attributes
                 a.href='#';
                 a.id=i;
                 a.style.fontFamily='Verdana';
                 a.style.fontSize='11px';
                 a.style.fontWeight='bold';
                 a.appendChild(document.createTextNode(i));

                 // append link to <div> container
                 div.appendChild(a);

                 // append blank space
                 div.appendChild(document.createTextNode(' '));

                 // assign onclick event handler to paging links
                 a.onclick=function(){

                   // update records list
                   displayRecords(this.id);

                   // update paging links
                   generateLinks(this.id);
                 }
               } 
               else{

                 // the current page is not linked
                var span=document.createElement('span');
                span.style.fontFamily='Verdana';
                span.style.fontSize='11px';
                span.style.fontWeight='bold';
                span.appendChild(document.createTextNode(i));
                div.appendChild(span);
              }
            }

            // create next link
            if(page<numPages){
              var a=document.createElement('a');
              a.href='#';
              a.id=parseInt(page)+1;
              a.style.fontFamily='Verdana';
              a.style.fontSize='11px';
              a.style.fontWeight='bold';
              a.appendChild(document.createTextNode('Next>>'));
              div.appendChild(a);
              a.onclick=function(){

                // update records list
                displayRecords(this.id);

                // update paging links
                generateLinks(this.id);
              }
            }

            // replace old links node with new links node
            linksDiv.parentNode.replaceChild(div,linksDiv);
          }

          // execute functions when page is loaded 
          window.onload=function(){
            if(document.getElementById&&document.createElement){

              // create containing <div> elements
              createDivs();

              // display records
              displayRecords(page);

              // generate paging links
              generateLinks(page);
            }
          }
    </script>
    <style type="text/css">
    /*define some styles*/

    p {
      font: bold 16px Arial, Helvetica, sans-serif;
      color: #000;
    }

    #records {
      width: 50%;
      background: #ccf;
      font: normal 12px "Arial", Helvetica, sans-serif;
      color: #000;
      border: 1px solid #000;
    }

    #records p {
      margin: 10px;
    }
    </style>
    </head>
    <body>
    <h1>Records Listing</h1>
    </body>
    </html>

    Wow, that was a lot of code! However, it's more than enough to show how the paging system works. Keep in mind that the example illustrates a basic structure, and improvements are just around the corner. We might work with different PHP files and then include them when necessary. The JavaScript code should be located in an external file, as well as the CSS styles. Whatever you want to do with the example is merely subject to your personal needs. Here's the output that I get from the browser, using the given example:

    The above screenshot looks like we're paginating records with some server-side language. However, the paging system is working only with JavaScript arrays. Use the code, create the files and test it in your Web server. It's something that you have to see for yourself. So, our job is finally done.

    Conclusion

    That's all for now. We're completed the series dealing with the PHP-JavaScript interaction, showing a couple of real-world examples, hopefully demonstrating that utilizing a PHP-JavaScript combination is quite powerful, at least, in controlled environments. Of course, when working on larger projects, server-side based solutions rule all the way. But, this technique has a place in our developer's toolbox as well. You have the power and the knowledge. Just take advantage of it!



     
     
    >>> 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 6 Hosted by Hostway
    Stay green...Green IT