Developing the Server-side Layer of an Email Application in AJAX
Here you have it. Welcome to the concluding part of the series “Take AJAX to your email inbox.” In three parts, this series shows in a friendly format how to develop a simple web-based POP3 client which uses AJAX as the driving technology for fetching and displaying email messages on a web document.
Developing the Server-side Layer of an Email Application in AJAX - Assembling the POP3 client: putting client and server-side layers to work together (Page 4 of 4 )
As I mentioned before, here's the first file that comprises the web-based POP3 client, "pop_client.htm," which interacts with the "PHP3Processor" class, in order to connect to the POP3 server and retrieve the list of email messages:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>AJAX-BASED POP3 CLIENT</title> <meta http-equiv="Content-Type" content="text/html; charset=iso- 8859-1" /> <script language="javascript"> var index=0; function sendHttpRequest(url,callbackFunc,respXml){ var xmlobj=null; try{ xmlobj=new XMLHttpRequest(); } catch(e){ try{ xmlobj=new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ alert('AJAX isn't 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('POST',url,true); // send http header xmlobj.setRequestHeader('Content-Type','application/x-www- form-urlencoded; charset=UTF-8'); // get form values and send http request xmlobj.send(getFormValues(document.getElementsByTagName ('form')[0])); } // get form values function getFormValues(fobj){ var str=''; for(var i=0;i< fobj.elements.length;i++){ str+=fobj.elements[i].name+'='+ escape(fobj.elements [i].value)+'&'; } str=str.substr(0,(str.length-1)); return str; } // fetch messages from POP3 server function fetchMessages(messages){ // build messages array var messages=messages.split('||||'); var mdiv=document.getElementById('mailcontainer'); if(!mdiv){return}; // display mail server response mdiv.innerHTML=messages[0]; // get 'previous' button var prev=document.getElementsByTagName('form')[1].elements ['prev']; if(!prev){return}; // get 'next' button var next=document.getElementsByTagName('form')[1].elements ['next']; if(!next){return}; // get 'clear' button var clear=document.getElementsByTagName('form')[1].elements ['clear']; if(!clear){return}; // move messages pointer back prev.onclick=function(){ index--; if(index<0){index=0}; mdiv.innerHTML=messages[index]; } // move messages pointer forward next.onclick=function(){ index++; if(index==messages.length){index=messages.length-1}; mdiv.innerHTML=messages[index]; } // clear mail container clear.onclick=function(){mdiv.innerHTML=''}; } // initialize user panel function initializeUserPanel(){ // get 'connect' button var sendbtn=document.getElementsByTagName('form')[0].elements['connect']; // send http request when button is clicked on sendbtn.onclick=function(){ // send request & fetch messages from POP3 server sendHttpRequest('http://pop_processor.php','fetchMessages'); // display 'Retrieving...' message var mdiv=document.getElementById('mailcontainer'); if(!mdiv){return}; mdiv.innerHTML='Retrieving messages from the server...'; } } // initialize user panel when page is loaded window.onload=function(){ // check if browser is DOM compatible if(document.createElement&&document.getElementById&&document. getElementsByTagName){ // initialize user panel initializeUserPanel(); } } </script> <style type="text/css"> body { margin: 10px 0 0 0; } #userinfo { width: 700px; height: 22px; padding: 2px 5px 2px 5px; border-top: 2px solid #000; border-left: 2px solid #000; border-right: 2px solid #000; background: #9cf; margin-left: auto; margin-right: auto; font: bold 11px Verdana, Arial, Helvetica, sans- serif; color: #000; } #mailcontainer { width: 700px; height: 520px; padding: 2px 5px 2px 5px; border: 2px solid #000; background: #eee; margin-left: auto; margin-right: auto; font: 12px normal Arial, Helvetica, sans-serif; color: #000; overflow: auto; } #navbar { width: 700px; height: 22px; padding: 2px 5px 2px 5px; border-left: 2px solid #000; border-right: 2px solid #000; border-bottom: 2px solid #000; background: #9cf; margin-left: auto; margin-right: auto; } form { display: inline; } .inputbox { width: 150px; border: 1px solid #000; background: #eee; } .formbutton { width: 70px; height: 20px; font: bold 11px Verdana, Arial, Helvetica, sans- serif; color: #000; } </style> </head> <body> <div id="userinfo"> <form> HOST <input name="host" type="text" class="inputbox" title="Enter mail hostname" /> USER <input name="user" type="text" class="inputbox" title="Enter username" /> PASSWORD <input name="pass" type="password" class="inputbox" title="Enter password" /> <input name="connect" type="button" value="Connect" class="formbutton" /> </form> </div> <div id="mailcontainer"> </div> <div id="navbar"> <form> <input name="prev" type="button" value="<< Prev" class="formbutton" title="Previous message" /> <input name="next" type="button" value="Next >>" class="formbutton" title="Next message" /> <input name="clear" type="button" value="Clear" class="formbutton" title="Clear all messages" /> </form> </div> </body> </html>
And below is the source code that corresponds to the "pop_processor.php" file:
<?php class POP3Processor{ // declare data members private $output=''; private $fp; // constructor public function __construct($host,$user,$password){ if(!$this->fp=fsockopen($host,110,$errno,$errstr,30)){ throw new Exception('Failed to connect to POP3 server '.$errstr.$errno); } stream_set_timeout($this->fp,2); $this->output.=fgets($this->fp,128).'<br />'; fputs($this->fp,"USER $usern");// send USER command $this->output.=fgets($this->fp,128).'<br />'; fputs($this->fp,"PASS $passwordn");// send PASS command $this->output.=fgets($this->fp,128).'<br />'; $this->output.='||||';// send delimiter string } // fetch email messages public function fetch(){ fputs($this->fp,"STATn");// send STAT command $ret=fgets($this->fp,128).'<br />'; if(substr($ret,0,5)!='-ERR '){ $messages=intval(substr($ret,4,1)); for($i=1;$i<=$messages;$i++){ fputs($this->fp,"RETR $in"); // send RETR command $this->output.=stream_get_contents($this- >fp).'<br /><br />';// fetch email messages $this->output.='||||';// send delimiter string } } $this->output=substr($this->output,0,strlen($this- >output)-4); return $ret.$this->output; } // close mail server connection public function close(){ fputs($this->fp,"QUITn"); fclose($this->fp); } } try{ // clean up POST data array_map('trim',$_POST); // instantiate POP3 processor object $popProc=new POP3Processor($_POST['host'],$_POST ['user'],$_POST['pass']); // fetch messages from mail server echo $popProc->fetch(); // close mail server connection $popProc->close(); } catch(Exception $e){ echo $e->getMessage(); exit(); } ?>
That's all the source code you need to copy and paste, in order to use the web-based POP3 client. I hope you enjoy the experience!
To wrap up
As I said before, we're done now. Over this three-part series I've demonstrated another possible implementation of AJAX, by creating a web-based POP3 client application, handy for retrieving and displaying email messages on a web document. Of course, the program is just a starting point for developing more complex projects, but you should have a clear idea of how to get started using AJAX for building desktop-like applications. Want to know more about web programming? Fine, see you in the next 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.