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. |