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

Building client-based result sets: making PHP and JavaScript interact - PHP

In the final article in our series about using PHP and JavaScript to store data on the client side, we will be building on what we learned about server and client interaction to create a JavaScript-based paginating system.

TABLE OF CONTENTS:
  1. PHP and JavaScript Interaction: Storing Data in the Client, part 3
  2. Records wanted! Fetching data from tables
  3. Defining data containers: the "createDivs()" function
  4. Showing database records: the "displayRecords()" function
  5. 1 - 2 - 3 Next
  6. Building paging links: the sequel
  7. Building client-based result sets: making PHP and JavaScript interact
By: Alejandro Gervasio
Rating: starstarstarstarstar / 14
May 18, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

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: