Sending Email with AJAX: Interacting with the Server
Here we are again. Welcome to the last tutorial of the series “Sending email with AJAX.” As you may have guessed regarding the title, this three-part series explains the development of a fairly simple AJAX-driven email client application, which offers some interesting capabilities for sending email, as well as for displaying and adding contacts, all without the need to involve page reloads.
Sending Email with AJAX: Interacting with the Server - Putting the layers together: listing the application’s source code, first section (Page 4 of 5 )
If you feel inclined to copy the complete code of the application and study it, then this is a good time to do precisely that. Here’s the source code for AJAX-driven email client, starting with the “ajaxmail.htm” file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>AJAX-DRIVEN MAIL CLIENT</title> <meta http-equiv="Content-Type" content="text/html; charset=iso- 8859-1"> <script language="javascript"> //***************************************** // // Description: Ajax-driven email client // Author: Alejandro Gervasio // Version: 1.0 // //***************************************** // getXMLHttpRequest object function getXMLHttpRequestObject(){ var xmlobj; // check for existing requests if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4){ xmlobj.abort(); } try{ // instantiate object for Mozilla, Nestcape, etc. xmlobj=new XMLHttpRequest(); } catch(e){ try{ // instantiate object for Internet Explorer xmlobj=new ActiveXObject('Microsoft.XMLHTTP'); } catch(e){ // Ajax is not supported by the browser xmlobj=null; return false; } } return xmlobj; } // request 'sendmail.php' file - sends email message function sendEmailRequest(){ var message=document.getElementsByTagName('form')[1].elements ['message'].value; if(message.length>1000){message=message.substring(0,1000)}; // open socket connection emailXMLHttpObj.open('POST','sendmail.php',true); // set form http header emailXMLHttpObj.setRequestHeader('Content- Type','application/x-www-form-urlencoded; charset=UTF-8'); // get form values and send http request emailXMLHttpObj.send(getFormValues (document.getElementsByTagName('form')[1])); emailXMLHttpObj.onreadystatechange=emailStatusChecker; } // check status of email requester object function emailStatusChecker(){ // if mail request is completed if(emailXMLHttpObj.readyState==4){ if(emailXMLHttpObj.status==200){ // if status == 200 display server response displayServerResponse(); } else{ alert('Failed to get response :'+emailXMLHttpObj.statusText); } } } // display server response function displayServerResponse(){ var status=document.getElementsByTagName('h1')[1].firstChild; if(!status){return}; // display messages by <h1> header status.data=emailXMLHttpObj.responseText; } // 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; } // get contact list function getContactList(){ // request 'contact.xml' file contactXMLHttpObj.open('GET','contacts.xml',true); contactXMLHttpObj.setRequestHeader('Content- Type','text/xml'); contactXMLHttpObj.send(null); contactXMLHttpObj.onreadystatechange=contactStatusChecker; } // check status of contact requester object function contactStatusChecker(){ // if request of 'contacts.xml' file is completed if(contactXMLHttpObj.readyState==4){ if(contactXMLHttpObj.status==200){ // if status == 200 display contact list displayContacts(); } else{ alert('Failed to get response :'+contactXMLHttpObj.statusText); } } } // display list of contacts function displayContacts(){ var cdiv=document.getElementById('contactlist')? document.getElementById('contactlist'):document.createElement('div'); cdiv.setAttribute('id','contactlist'); // reset contacts container cdiv.innerHTML=''; // read 'contacts.xml' file var contacts=contactXMLHttpObj.responseXML.getElementsByTagName ('contact'); if(!contacts){return}; var ul=document.createElement('ul'); for(var i=0;i<contacts.length;i++){ // create contact links var li=document.createElement('li'); var a=document.createElement('a'); // get 'email' value var email=contacts[i].getElementsByTagName('email') [0].firstChild.nodeValue; // add 'href' attribute a.setAttribute('href','#'); // add 'title' attribute a.setAttribute('title',email); // add contact labels a.appendChild(document.createTextNode(contacts [i].getElementsByTagName('name')[0].firstChild.nodeValue)); // fill form fields when contact is clicked on a.onclick=function(){fillEmailFields(this.title)}; li.appendChild(a); ul.appendChild(li); cdiv.appendChild(ul); } // append contact links to web document document.getElementById('contsection').appendChild(cdiv); } // add new contact function addContact(){ // create containing div var cdiv=document.createElement('div'); // create 'fullname' field var fullname=document.createElement('input'); fullname.setAttribute('type','text'); fullname.setAttribute('name','fullname'); fullname.setAttribute('value','Enter Full Name'); fullname.className='contfield'; fullname.onfocus=function(){this.value=''}; // create 'email' field var emailaddr=document.createElement('input'); emailaddr.setAttribute('type','text'); emailaddr.setAttribute('name','email'); emailaddr.setAttribute('value','Enter Email Address'); emailaddr.className='contfield'; emailaddr.onfocus=function(){this.value=''}; // create 'done' button var donebtn=document.createElement('input'); donebtn.setAttribute('type','button'); donebtn.setAttribute('name','sendcontact'); donebtn.setAttribute('value','Done'); donebtn.className='mailbutton'; // append form fields to containing div cdiv.appendChild(fullname); cdiv.appendChild(emailaddr); cdiv.appendChild(donebtn); // get 'addContact" button addbtn=document.getElementsByTagName('form')[0].elements ['add']; // replace 'addContact' button with div addbtn.parentNode.replaceChild(cdiv,addbtn); // insert contact into 'contacts.xml' file donebtn.onclick=function(){ insertXMLHttpObj.open('POST','addcontact.php',true); // set form http header insertXMLHttpObj.setRequestHeader('Content- Type','application/x-www-form-urlencoded; charset=UTF-8'); // get form values and send http request insertXMLHttpObj.send(getFormValues (document.getElementsByTagName('form')[0])); // replace back containing div with 'addContact" button cdiv.parentNode.replaceChild(addbtn,cdiv); // refresh contact list getContactList(); } } // fill form field with contact values function fillEmailFields(email){ var to=document.getElementsByTagName('form')[1].elements ['to']; if(!to){return}; var cc=document.getElementsByTagName('form')[1].elements ['cc']; if(!cc){return}; var bcc=document.getElementsByTagName('form')[1].elements ['bcc']; if(!bcc){return}; if(to.value=='TO: '||!to.value){to.value='TO: '+email;return}; if(cc.value=='CC: '||!cc.value){cc.value='CC: '+email;return}; if(bcc.value=='BCC: '||!bcc.value){bcc.value='BCC: '+email;return}; } // initialize email client function intitializeEmailClient(){ if(document.getElementById&&document. getElementsByTagName&&document.createElement){ var sendbtn=document.getElementsByTagName('form') [1].elements['send']; if(!sendbtn){return}; // assign 'onlick' event handler to 'send' button sendbtn.onclick=function(){ // display message document.getElementsByTagName('h1') [1].firstChild.data='STATUS: SENDING MESSAGE...'; // send email request sendEmailRequest(); } var clearbtn=document.getElementsByTagName('form') [1].elements['clear']; if(!clearbtn){return}; // assign 'onlick' event handler to 'clear message' button clearbtn.onclick=function(){document.getElementsByTagName ('h1')[1].firstChild.data='STATUS: COMPOSING NEW MESSAGE'}; var contactbtn=document.getElementsByTagName('form') [1].elements['contact']; if(!contactbtn){return}; // assign 'onlick' event handler to 'contact' button contactbtn.onclick=getContactList; var addbtn=document.getElementsByTagName('form') [0].elements['add']; // assign 'onlick' event handler to 'add Contact' button addbtn.onclick=addContact; // display contact list getContactList(); } } // instantiate email XMLHttpRequest object var emailXMLHttpObj=getXMLHttpRequestObject(); // instantiate contact XMLHttpRequest object var contactXMLHttpObj=getXMLHttpRequestObject(); // instantiate insert XMLHttpRequestObject var insertXMLHttpObj=getXMLHttpRequestObject(); window.onload=intitializeEmailClient; </script> <style type="text/css"> body { margin: 0; padding: 0; } h1 { font: bold 16px Arial, Helvetica, sans-serif; margin: 5px; } a:link,a:visited { display: block; width: 120px; padding: 2px 0 2px 5px; font: bold 12px Verdana, Arial, Helvetica, sans- serif; color: #00f; text-decoration: none; border: 1px solid #cc3; } a:hover { color: #f33; background: #fff; border: 1px solid #000; } form { display: inline; } textarea { width: 575px; height: 380px; margin-left: 5px; background: #ffc; border: 1px solid #000; } #container { width: 800px; height: 572px; padding: 5px; margin-left: auto; margin-right: auto; background: #cc9; border: 1px solid #000; } #mailsection{ float: left; width: 590px; height: 570px; margin-left: 5px; background: #cc3; border: 1px solid #000; } #contsection { float: left; width: 200px; height: 570px; background: #cc3; border: 1px solid #000; overflow: auto; } .mailfield { width: 575px; height: 20px; margin: 0 0 5px 5px; border: 1px solid #000; background: #ffc; font: bold 11px Verdana, Arial, Helvetica, sans- serif; color: #000; } .mailbutton { width: 120px; height: 25px; margin-left: 5px; font: bold 11px Verdana, Arial, Helvetica, sans- serif; color: #000; } .contfield { width: 185px; height: 20px; margin: 0 0px 5px 5px; border: 1px solid #000; background: #ffc; font: bold 11px Verdana, Arial, Helvetica, sans- serif; color: #000; } </style> </head> <body> <div id="container"> <div id="contsection"> <h1>CONTACT LIST</h1> <form> <input name="add" type="button" value="Add Contact" class="mailbutton" title="Add new contact" /> </form> </div> <div id="mailsection"> <h1>STATUS: COMPOSING NEW MESSAGE</h1> <form> <input name="subject" type="text" value="SUBJECT: " class="mailfield" title="Enter message's subject" /> <input name="to" type="text" value="TO: " class="mailfield" title="Enter recipient's email address" /> <input name="cc" type="text" value="CC: " class="mailfield" title="Enter email address for carbon copy" /> <input name="bcc" type="text" value="BCC: " class="mailfield" title="Enter email address for blind carbon copy" /> <textarea name="message" title="Type your message here" /></textarea> <input name="send" type="button" value="Send Message" class="mailbutton" title="Send Message" /> <input name="clear" type="reset" value="Clear Message" class="mailbutton" title="Clear Message" /> <input name="contact" type="button" value="Display Contacts" class="mailbutton" title="Display Contact List" /> </form> </div> </div> </body> </html>