Coding of Web email client based on AJAX technology

Source: Internet
Author: User
[Guide] In this article, we will comprehensively analyze the application layer of the Web-based POP3 client program in this series, namely, JavaScipt encoding.

I. Introduction

In the first article, we constructed the POP3 client user interface, the general goal of this series of articles. To create the basic visual structure of the mail application, I have defined the (X) HTML Tag and the corresponding CSS declaration. In addition, I have also summarized the general definitions of each function at the client application layer. In fact, these functions are responsible for implementing many functions, such as sending POP3 commands to the PHP file of the mail server, controlling the behavior of each component in the user interface we defined earlier, and so on.

Before extracting mail messages that will be displayed on the web page from the mail server, I must develop an appropriate JavaScript layer to allow me to add some features to the frontend of this POP3 program, because you must be very curious about how to establish a connection from the client application to the mail server, and how to add actions on the navigation buttons as part of the user interface.

In this article, I will fully define the JavaScript Functions you have seen in the first article. I hope that at the end of this article, you will have a set of functions that can retrieve messages that will be displayed on the web page from a given email server. You should also be able to create a simple navigation mechanism for switching between messages.

After clarifying the objectives of this article, let's start the specific coding of the Client layer of this series of demos.

2. Connect to the email server-define the sendHttpRequest () function

To make things as simple as possible, the process of connecting to the mail server is implemented using AJAX technology. This means that I have to process the XMLHttpRequest object and its related attributes. In this way, all connection tasks can be processed without disturbing the entire application with too complex JavaScript code.

Next, we will discuss the function sendHttpRequest (), which will send a request to the PHP file responsible for connecting to the mail server and retrieve the email message. It is defined as follows:

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 the socket connection

Xmlobj. open ('post', url, true );

// Send the http Header

Xmlobj. setRequestHeader ('content-type', 'application/x-www-

Form-urlencoded; charset = UTF-8 ');

// Obtain the form value and send an http request

Xmlobj. send (getFormValues (document. getElementsByTagName

('Form') [0]);


If you have used AJAX technology in previous Web applications, you should be very familiar with the above functions. As you can see, it has three input parameters: the URL pointing to the script, the called callback function name (callbackFunc), an XML tag (respXML) when the http request is complete) -It instructs the function whether server data should be retrieved in XML format.

After explaining the meaning of the input parameters, let's further analyze how to use them in the function. The main purpose of the above function is to retrieve a PHP file from the Web server. Then, it instantiates an XMLHttpRequest object after resolving the mismatch between Internet Explorer and other browsers.

You should remember that the user interface I created in the connection section is designed as a simple web form. Therefore, this function must send data input from this form to establish a connection to the mail server, this is achieved by activating a POST request to the server and specifying the corresponding HTTP header (it tells the server to process the data just like the data submitted through a regular form.

It is worth noting that. See the following code line:

Xmlobj. send (getFormValues (document. getElementsByTagName ('form ')


As you can see, after using the getFormValues () function to collect the input values in the form, this function sends a POST request to send the data extracted from the form to the server. However, I am a little anxious because this function is not defined yet. Therefore, after explaining the working principle of the sendHttpRequest () function, we will create this new function.

3. Collect connection data-define the getFormValues () function

As mentioned above, the getFormValues () function is used to obtain user input data after a connection is established to the mail server. That is, get the email server name or IP address, together with the corresponding user name/password combination (they will be converted to "var1 = value1 & var2 = value2... & varN = valueN "format ).

This task is very simple. The following is a complete list of functions:

function getFormValues(fobj){

var str='';

for(var i=0;i< fobj.elements.length;i++){

str+=fobj.elements[i].name+'='+ escape(fobj.elements




return str;


Here, the function receives the Web form to be processed as an input parameter and cyclically traverses each of its fields to obtain the corresponding domain data. After traversing the form data, this function returns the form value to the calling code using a properly formatted string.

Now, I have shown you how the POP3 client connects to the mail server after the correct data combination is submitted. However, assuming that the connection has been successfully established, how can I display the email message on the web page? To answer this question, I will define another useful function, fetchMessages (), which is used to display and retrieve messages from the mail server.

Next, let's analyze how this function works.
Iv. Display email messages-define the fetchMessages () function

First, I declare the function code first. Note that the previously created function sendHttpRequest () can call a callback function after the HTTP request ends to process the response from the server. In this case, I will use fetchMessages () as the callback function that will be called after an email message is retrieved from the email server so that the messages can be correctly displayed on the webpage.

Now you know the purpose of this function and how it is used in applications. Next, let's take a look at its specific definition:

Function fetchMessages (messages ){

// Construct a message Array

Var messages = messages. split ('| ');

Var mdiv = document. getElementById ('mailcontainer ');

If (! Mdiv) {return };

// Display the email server response

Mdiv. innerHTML = messages [0];

// Get the 'previous' button

Var prev = document. getElementsByTagName ('form') [1]. elements


If (! Prev) {return };

// Get the 'Next' button

Var next = document. getElementsByTagName ('form') [1]. elements


If (! Next) {return };

// Get the 'clear' button

Var clear = document. getElementsByTagName ('form') [1]. elements


If (! Clear) {return };

// Move the message pointer backward

Prev. onclick = function (){

Index --;

If (index <0) {index = 0 };

Mdiv. innerHTML = messages [index];


// Move the message Pointer Forward

Next. onclick = function (){

Index ++;

If (index = messages. length) {index = messages. length-1 };

Mdiv. innerHTML = messages [index];


// Clear the mail container

Clear. onclick = function () {mdiv. innerHTML = ''};


The above functions are worth noting. The first point is that it uses the e-mail message as the unique input parameter (messages) for later processing. It may be annoying to process email messages because the PHP code running on the server has not been created so far. However, you don't have to worry about this because I will explain this part of PHP code in the last article.

At this point, we know that all email messages will be retrieved in string form through the responseText attribute of the corresponding request object, then it is stored as an array structure-each Message corresponds to an array element. This task is easy to implement. You can use the "|" (four pipeline symbols) separator to break down messages, so that messages can be processed separately.

This process is implemented by the following line:

Var messages = messages. split ('| ');

Here, we must be very careful because the message formats scheduled by different POP3 mail servers may be slightly different. To ensure that message retrieval can work on most POP3 mail servers, I use four pipeline delimiters, but you can use other symbols, this depends on the specific needs of each type of server.

The result of this function code is easy to understand. Since all messages will be displayed in the "mailcontainer" DIV Section (as defined in the previous article ), this function will display the initial server response (stored as the first element of the messages array (messages [0]), and then assign various actions to each navigation button.

To switch back and forth between messages, the "prev" and "next" buttons will increase or decrease an "Index" message pointer each time you click them, this will cause a new message to be generated immediately each time. As you can see, this navigation mechanism is very simple and effective.

Similarly, by using the following function, the "Clear" button resets the content of the "mailcontainer" DIV:

Clear. onclick = function () {mdiv. innerHTML = ''};

As you can see, the fetchMessages () function executes some very useful tasks, such as displaying email messages and implementing a simple navigation system. Next, I also need to define the last function of the POP3 application to initialize the POP3 client after loading the webpage. Next we will discuss this function.

5. initialize the POP3 client-define the initializeUserPanel () function

The initializeUserPanel () function in this section initializes the POP3 client, which is defined below:

Function initializeUserPanel (){

// Get the 'connect' button

Var sendbtn = document. getElementsByTagName ('form') [0]. elements

['Connect '];

// Send an http request when you click the button

Sendbtn. onclick = function (){

// Send a request and retrieve the message from the POP3 server

SendHttpRequest ('pop _ processor. php', 'fetchmessages ');

// Display the 'retrieving... 'message

Var mdiv = document. getElementById ('mailcontainer ');

If (! Mdiv) {return };

Mdiv. innerHTML = 'retrieving messages from the server ...';



The above function binds the sendHttpRequest () function to the connect button to activate the HTTP request when you click this button. Note: Here I pass in the form of a parameter the PHP file that is responsible for connecting and retrieving e-mail messages, the connection callback function (fetchMessages ()-it is responsible for processing and displaying messages on the web page.

The last function of this function is to display the message "Retrieving messages from the server..." when processing connections to the mail server and running message retrieval in the background ...".

So far, I have shown you all JavaScript Functions-they constitute the entire Web-based POP3 client, which means that we have developed the entire client application layer. For the complete JavaScript function code, refer to the source code file attached to this article (detailed annotations have been added ).

Vi. Summary

In this article, we analyze all the JavaScript Functions that constitute the entire POP3 client program. However, we also need to connect to the server. To this end, we will discuss in the next article (last) of this series how to build a PHP file to connect to the POP3 mail server.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.