JavaScript
  Home arrow JavaScript arrow Page 4 - 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  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
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 - Putting all the pieces together


    (Page 4 of 4 )

    As I promised in the section that you just read, below I listed the full source code that corresponds to this database-driven application, in conjunction with the output generated by it, naturally using the database records that you saw previously.

    Here is the complete source code for this application:

    (definition of "fetchrows.php" file)

    <?php
    // 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');
        
    }
      
    }
    }
    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();
    }
    ?>
    <script language="javascript">
    // send http requests
    function sendHttpRequest(url,callbackFunc,respXml){
      
    var xmlobj=null;
      
    try{
        
    xmlobj=new XMLHttpRequest();
      
    }
      
    catch(e){
        
    try{
          
    xmlobj=new ActiveXObject("Microsoft.XMLHTTP");
        
    }
        
    catch(e){
          
    alert('AJAX is not supported by your browser!');
          
    return false;
         
    }
      
    }
      
    xmlobj.onreadystatechange=function(){
        
    if(xmlobj.readyState==4){
          
    if(xmlobj.status==200){
            
    respXml?eval(callbackFunc+'(xmlobj.responseXML)'):eval
    (callbackFunc+'(xmlobj.responseText)');
          
    }
        
    }
      
    }
      
    // open socket connection
      
    xmlobj.open('GET',url,true);
      
    // send http header
      
    xmlobj.setRequestHeader('Content-Type','text/html;
    charset=UTF-8');
      
    // send http request
      
    xmlobj.send(null);
    }
    function showDetails(results){
      
    if(results){
        
    var divid=results.split('|')[0];
        
    var result=results.split('|')[1];
        
    var artdiv=document.getElementById('article'+divid);
        
    if(divid){
          
    var div=document.createElement('div');
          
    div.appendChild(document.createTextNode(result));
          
    artdiv.appendChild(div);
        
    }
      
    }
    }
    var artcont=document.getElementById('articlecontainer');
    if(artcont){
      
    var links=artcont.getElementsByTagName('a');
     
    if(links){
       
    for(var i=0;i<links.length;i++){
         
    links[i].onclick=function(){
           
    sendHttpRequest('showdetail.php?id='+this.href.split('?')
    [1].substring(3),'showDetails');
           
    this.href='#';
          
    }
       
    }
     
    }
    }
    </script>

    (definition of "showdetails.php" file)

    <?php

    // 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');
        
    }
       
    }
    }
    try{
      
    // connect to MySQL
      
    $db=new MySQL(array('host'=>'host','user'=>'user',
    'password'=>'password','database'=>'database'));
      
    $id=$_GET['id'];
      
    $result=$db->query("SELECT content FROM articles WHERE
    id='$id'");
      
    while($row=$result->fetchRow()){
        
    echo $id.'|'.$row['content'];
      
    }
    }
    catch(Exception $e){
      
    echo $e->getMessage();
      
    exit();
    }
    ?>

    As you can see, now the full contents of a concrete article are displayed on the same web page that shows the articles' tiles and authors respectively. Of course it will happen this way only if JavaScript is enabled on the browser. Otherwise, users still will be able to see the content, but on a different web document.

    Final thoughts

    Finally, we've come to the end of this series. I hope that you analyze in detail all the practical examples shown here, so you can use them as a source of inspiration for creating JavaScript applications that degrade gracefully.

    See you in the next web development tutorial!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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

    JAVASCRIPT ARTICLES

    - 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
    - Ajax Hack for Entering Information Without R...
    - EXT JS 2.1 Overview
    - Using the Style Object for Zebra Tables with...
    - Binary Searching
    - An Improved Approach to Building Zebra Tables
    - Assigning Background Colors Dynamically to Z...
    - Building Zebra Tables with CSS and JavaScript
    - JavaScript: Array Objects
    - A Closer Look at Smart Markers with Yahoo! M...
    - Using Polylines and Smart Markers with Yahoo...







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway