JavaScript
  Home arrow JavaScript arrow Page 2 - Making JavaScript Applications Degrade Gra...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
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? 
JAVASCRIPT

Making JavaScript Applications Degrade Gracefully with AJAX and MySQL
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2007-07-02

    Table of Contents:
  • Making JavaScript Applications Degrade Gracefully with AJAX and MySQL
  • Fetching database rows using a typical approach
  • Displaying additional database records with AJAX
  • Putting all the pieces together

  • 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


    Making JavaScript Applications Degrade Gracefully with AJAX and MySQL - Fetching database rows using a typical approach


    (Page 2 of 4 )

    In order to demonstrate how to retrieve some basic database records from MySQL using a combination of PHP and AJAX, I'm going to define a pair of PHP classes which will be tasked with connecting and sending queries to the server, as well as handling the returned result sets.

    Actually, I used these classes in some of my previous PHP tutorials, so possibly at this point you'll find them very familiar. Having said that, here is how the classes in question look:

    // define 'MySQL' class
    class MySQL{
      
    private $conId;
      
    private $host;
      
    private $user;
      
    private $password;
      
    private $database;
      
    private $result;
      
    const OPTIONS=4;
      
    public function __construct($options=array()){
        
    if(count($options)!=self::OPTIONS){
          
    throw new Exception('Invalid number of connection
    parameters');
         
    }
        
    foreach($options as $parameter=>$value){
          
    if(!$value){
            
    throw new Exception('Invalid parameter '.$parameter);
          
    }
          
    $this->{$parameter}=$value;
         
    }
        
    $this->connectDB();
      
    }
      
    // connect to MySQL
      
    private function connectDB(){
        
    if(!$this->conId=mysql_connect($this->host,$this-
    >user,$this->password)){
          
    throw new Exception('Error connecting to the server');
        
    }
         
    if(!mysql_select_db($this->database,$this->conId)){
          
    throw new Exception('Error selecting database');
        
    }
      
    }
      
    // run query
      
    public function query($query){
        
    if(!$this->result=mysql_query($query,$this->conId)){
          
    throw new Exception('Error performing query '.$query);
        
    }
        
    return new Result($this,$this->result);
      
    }
    }
    // define 'Result' class
    class Result {
      
    private $mysql;
      
    private $result;
      
    public function __construct(&$mysql,$result){
        
    $this->mysql=&$mysql;
        
    $this->result=$result;
      
    }
      
    // fetch row
      
    public function fetchRow(){
        
    return mysql_fetch_assoc($this->result);
      
    }
      
    // count rows
      
    public function countRows(){
        
    if(!$rows=mysql_num_rows($this->result)){
          
    throw new Exception('Error counting rows');
        
    }
        
    return $rows;
      
    }
      
    // count affected rows
      
    public function countAffectedRows(){
        
    if(!$rows=mysql_affected_rows($this->mysql->conId)){
          
    throw new Exception('Error counting affected rows');
        
    }
        
    return $rows;
      
    }
      
    // get ID form last-inserted row
      
    public function getInsertID(){
        
    if(!$id=mysql_insert_id($this->mysql->conId)){
          
    throw new Exception('Error getting ID');
        
    }
        
    return $id;
      
    }
      
    // seek row
      
    public function seekRow($row=0){
        
    if(!is_int($row)||$row<0){
          
    throw new Exception('Invalid result set offset');
        
    }
        
    if(!mysql_data_seek($this->result,$row)){
          
    throw new Exception('Error seeking data');
        
    }
      
    }
    }

    Now that you've hopefully familiarized yourself with the signature of the PHP classes shown above, I'm going to create a sample "ARTICLES" MySQL database table, which will be filled in with the following data:

    Id title                                 author           content

    1 This is the title of article 1 Mary Wilson           This is the content of article 1

    2 This is the title of article 2 Alejandro Gervasio This is the content of article 2

    3 This is the title of article 3 John Doe                This is the content of article 3

    So far, so good. Having at our disposal the previous MySQL database table, the next thing to do here consists of displaying part of the above records on the browser, by using the following PHP script:

    try{
      
    // connect to MySQL
      
    $db=new MySQL(array('host'=>'localhost','user'=>'user',
    'password'=>'password','database'=>'database'));
      
    $result=$db->query("SELECT id,title,author FROM articles");
      
    echo '<h2>Article List</h2><div id="articlecontainer">';
      
    while($row=$result->fetchRow()){
        
    echo '<div id="article'.$row['id'].'">';
        
    echo 'Title: '.$row['title'].'<br /> Author: '.$row
    ['author'].'<a href="showdetail.php?id='.$row['id'].'"> Read
    more</a>';
        
    echo'</div><hr />';
      
    }
      
    echo '</div>';
    }
    catch(Exception $e){
       
    echo $e->getMessage();
      
    exit();
    }

    As you can see, the above PHP script simply displays part of the data stored in the "ARTICLES" database table that you saw before, including the respective articles' titles and authors. However I decided to include a link called "showdetail.php." It shows the full contents of the mentioned articles in a different web page. Quite simple, right?

    Additionally, the output generated by the previous PHP script can be seen clearly in the following screen shot:

    All right, at this point I built a simple PHP application that retrieves the contents of a sample "ARTICLES" MySQL database table, and then displays this data on the browser, of course including an additional link for showing the complete contents of these articles in a different web page.

    Maybe at this point you're asking yourself the following question: where does AJAX fit into the previous schema? I'm glad you asked! Suppose that instead of displaying the full contents of a certain article on a separate web page, you want to show this data on the same web document to make this process a bit more attractive to users.

    Here's where AJAX comes in. It's possible to develop a simple JavaScript application that displays the entire contents of a given article on the same web page. Nonetheless, the most important thing to notice here is the manner in which I built the original PHP application, which is completely independent of JavaScript.

    If eventually there's a user that has disabled JavaScript on the browser, he or she will still be able to see the contents of a specific article on another web page, because the AJAX-based routines will degrade gracefully. Now, did you grasp the concept surrounding the development of JavaScript applications that fail silently? I bet you did!

    Considering that you already understand the way that the previous PHP classes work, in the following section I'm going to create a simple AJAX-based script which will be responsible for displaying the full contents of a chosen article on the same web page on which the respective titles and authors are shown.

    To see how this will be achieved, please click on the link below and keep reading.

    More JavaScript Articles
    More By Alejandro Gervasio


       · Over the course of this last installment of the series, a simple MySQL-based...
     

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT