Broad Network


Client Web Code for Live Text Chart using Perl and MySQL Server

Web Live Text Chart Application using Perl and MySQL - Part 4

Web Development with Perl and MySQL

Foreword: In this part of the series I explain the code in the client conversation HTML document. The document is the content of one web page; in other words, there are no frames.

By: Chrysanthus Date Published: 9 Sep 2016

Introduction

This is part 4 of my series, Web Live Text Chart Application using Perl and MySQL. In this part of the series I explain the code in the client conversation HTML document. The document is the content of one web page; in other words, there are no frames.

The Client HTML Document without Scripts
The client HTML document without scripts is:

<!DOCTYPE HTML>
<html>
<head>
    <title>Live Chart of Company</title>
</head>
<body style="background-color:bisque">
<h3>Company Live Chart</h3>
An operator will contact you shortly.
<div id="D1">

</div>
    <span style="color:blue" id="SP1"></span><br>
    <textarea cols='45' rows='5' onkeyup="writing()" disabled id="TA1">
    </textarea>

<button type="button" style="float:right" onclick="sendMsg()">Send</button>

</body>
</html>

The client types in the text area. He then clicks the Send Button. The Send Button calls the Ajax function, sendMsg(), which sends the message to the server database. From there the operator web page reads the message. The text area is initially disabled, to prevent the client from typing and sending massage without being sure that an operator is available (present-live) at the other end.

The messages from the client and the operator are displayed in the DIV element dynamically. When the operator is typing, the span element of this client document is given the text, “Agent is typing…” dynamically. The operator may reflect on a response for a long time or in theory abandon the conversation or the connection may be broken. With this span element, the client would be confident that the operator is still there.

Scripts
The rest of the code of the client document consists of scripts. There are 5 ECMAScripts.

Script in Header
The HTML document header has a script. This script has global variables used by the other scripts. The script is:

    <script type="text/ECMAScript">
        //useful variables
        operator = "";
        operatorStart = ""; //operator is the one to send the first message
        divContent = "";
    </script>

The variable, operator, will have the actual name of the operator, such as “Peter”. You have the variable, operatorStart. The operator is the one to send the first message. When the first message is received, this variable would hold the value, "started". The variable, divContent holds the content (except the <dl> and </dl> tags) that goes into the div element. Remember, the HTML div element displays the messages from the client and from the operator. Both messages are housed in a dl element as indicated in one of the previous parts of this series.

Script for Clearing the Text Area at Startup
When the client HTML document is loaded into the browser, the text area may have some initial tab consisting of spaces (&nbsp; &nbsp; &nbsp; &nbsp;). You do not need this tab. So, the following script clears the text area when the document is loaded.

<script type="text/ECMAScript">
    //clear textarea
    document.getElementById('TA1').value = "";
</script>

Script for Reading Operator Message
The script for reading operator message is given below. It has an Ajax function that reads the message from the server. The Ajax function is called every 10 seconds by a timer function. If there is a recent message from the operator at the database, the Ajax function gets it. If there is no recent message, or the operator is not typing, the Ajax function gets nothing. The script is:

<script type="text/ECMAScript">

    function timeIntervalfn()
        {
            //call writing function
            writin();

            var myAjax;

            if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    myAjax = new XMLHttpRequest();
                }
            else
                {// code for IE5, IE6
                    myAjax = new ActiveXObject("Microsoft.XMLHTTP");
                }

            myAjax.onreadystatechange=function()
                {
                    if (myAjax.readyState == 4)
                         {
                            if (myAjax.status == 200)
                                {
                                    returnString = myAjax.responseText;
                                    arr = returnString.split(/&/);
                                    operatorPair = arr[0].split(/=/);
                                    operator = operatorPair[1];
                                    returnMessagePair = arr[1].split(/=/);
                                    returnMessage = returnMessagePair[1];
                                    writingPair = arr[2].split(/=/);
                                    writing = writingPair[1];
                                    operatorStartPair = arr[3].split(/=/);
                                    operatorStart = operatorStartPair[1];
                                    if (writing == "Yes")
                                        document.getElementById('SP1').innerHTML = "&nbsp;Agent is typing. . .";
                                    if ((returnMessage!="")&&(returnMessage!=null))
                                        {
                                            divContent += "<dt style='color:crimson'><strong>" + operator + "</strong></dt><dd style='color:brown'>" + returnMessage + "</dd>";
                                            document.getElementById('D1').innerHTML = "<dl>" + divContent + "</dl>";
                                            //clear typing indication of Span element
                                            document.getElementById('SP1').innerHTML = "";
                                        }
                                }
                         }
                    else
                        {
                         //alert error – to the client.
                        }
                }

            myAjax.open("GET", "http://localhost/clientRead.pl", true);
            myAjax.send(null);

            //enable textarea
            if (operatorStart == "started")
                {
                    document.getElementById('TA1').disabled = false;
                }
        }

        ti = window.setInterval("timeIntervalfn()", 10000);
</script>

The time interval function that calls the Ajax function every 10 seconds is:

        ti = window.setInterval("timeIntervalfn()", 10000);

The name of the Ajax function is "timeIntervalfn()" and it is the first argument of the timer interval function (it is in quotes). The second argument is the interval in milliseconds. So 10 seconds is 10000, typed without the digit-grouping comma.

The first statement in the Ajax function body is a call to another Ajax function outside the script, but in the same HTML document. This function call is, writin() for writing, without the g in “writing”. This writin() function will send information to the server to indicate that the client is typing a new message in the Text Area element.

Next in the Ajax function body is the declaration of the variable of the Ajax object. The code segment after, instantiates the Ajax object.

When there is no recent message in the database of the server or the operator is not typing, the responseText of the Ajax function is empty. I will explain later how the recent message is differentiated from an old message. The responseText message is of the name/value pair form, that is:

    operatorName=value&msg=value&operatorWriting=value&operatorStart=value

Note that this form of Ajax responseText does not have the initial ? sign. It does not have to, because this is a custom responseText. The split() function of the ECMAScript Regular Expression segment, splits the responseText data about & and splits the name/value pair about =.

For simplicity, the application has been written such that the name, operatorName of the responseText will always have the actual name of the operator, e.g. Peter. The name, msg of the responseText will always have the recent message from the operator. The name, operatorWriting will always have the value, “Yes” for operator typing or “No” for operator not typing. The name, operatorStart will have the value, “started” if the message sent by the operator is his first massage. If it is not his first message, the value will be something else.

In the Ajax responseText code segment, if the value of the local variable, writing, is “Yes” it means the operator is writing, so the code displays the text, “Agent is typing. . .” in the span element. Still in the code segment, if there is a recent message from the operator, the recent message is joined to all the previous messages of the client and operator, with the corresponding HTML tags, and sent to replace the content of the div element. When this is done, it means the recent message that the operator was typing (writing) has been read. And so the content of the span element is erased (given the value “”). Also note that in the code, one statement gives the content of the divContent variable and another statement displays the complete messages in the div element.

The next code segment in the Ajax function, reads the message from the server by calling the Perl “clientRead.pl” script file at the server. No data is sent to the server, by this function. The last code segment in the function, checks if the message received from the operator is the first message (with value “started”). If it is, the Text Area element is enabled so that the client can be sending his own messages, knowing that the operator is at the other end (live).

The Script for Sending Client Messages
When the client has typed the message in the Text Area element he clicks the Send Button. Clicking the Send Button calls the function sendMsg() of this script. The function is the only content of the script. Each time the button is clicked, the function sends the actual name of the client (e.g. John) to the server database. For simplicity, the actual name of the client is sent (along side the message) each time the button is clicked. The script is:

<script type="text/ECMAScript">
    function sendMsg()
        {
            //Prepare and add message with tags to store
            //Also send message to server with Ajax

            firstname = sessionStorage.firstname;

            msg = document.getElementById('TA1').value;
            if ((msg == "")||(msg == null))
                return;
            document.getElementById('TA1').value = ""; //clear text area
            //add message with tags to store
            divContent += "<dt style='color:darkslateblue'><strong>" + firstname + "</strong></dt><dd>" + msg + "</dd>";
            document.getElementById('D1').innerHTML = "<dl>" + divContent + "</dl>";


            //ajax code
            var ajaxObj;

            if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    ajaxObj = new XMLHttpRequest();
                }
            else
                {// code for IE5, IE6
                    ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
                }

            ajaxObj.onreadystatechange=function()
             {
                if (ajaxObj.readyState == 4)
                 {
                     if (ajaxObj.status == 200)
                         {
                            //
                         }
                 }
             else
                 {
                     //alert error – to the client.
                 }
             }

            URL = "http://localhost/clientMessage.pl" + "?firstname=" + firstname + "&msg=" + msg;
            ajaxObj.open("GET", URL, true);
            ajaxObj.send(null);

        }
</script>

Remember, when the client filled the form (first document of his window), his name was stored in his client computer as a property of a sessionStorage object. Note that the storage objects have replaced cookies.

The first line in the function, reads the actual name of the client from the sessionStorage object. The next line reads the content of the Text Area element into the variable, msg. Now, if the Text Area content was empty, then the rest of the function is not executed. This is taken care of by the next statement, which is an if-statement. The main aim of the function is to send the recently typed message to the server database. So, if nothing has been typed, the rest of the code is not executed.

After reading the content of the Text Area element, the element has to be cleared. The next statement handles this. After that the value of the variable of the div content, divContent is updated (added the new content); the HTML tags are also included appropriately. Note how this is done in the code. The next statement replaces the content of the div element. The new content has all the previous messages plus the new message of the client. The start and end dl tags are also included.

The rest of the code is the Ajax code. It sends the name of the client and the recently typed message of the client to the server database. There is no responseText code segment as no response is expected from the server. The main aim of the function with its Ajax code, is to send the recently typed message to the server. The name of the file that receives the data at the server is, clientMessage.pl.

Script to Indicate Client is Typing
The script to indicate that the client is writing is:

<script type="text/ECMAScript">

    function writin()
        {
            if (document.getElementById('TA1').value != "")
                {
                    //ajax code
                    var ajaxWObj;

                    if (window.XMLHttpRequest)
                        {// code for IE7+, Firefox, Chrome, Opera, Safari
                            ajaxWObj = new XMLHttpRequest();
                        }
                    else
                        {// code for IE5, IE6
                            ajaxWObj = new ActiveXObject("Microsoft.XMLHTTP");
                        }

                    ajaxWObj.onreadystatechange=function()
                        {
                            if (ajaxWObj.readyState == 4)
                                {
                                 if (ajaxWObj.status == 200)
                                     {
                                        //
                                     }
                                }
                            else
                                {
                                 //alert error – to the client.
                                }
                     }

                    write = "Yes";
                    URL = "http://localhost/clientWriting.pl" + "?writing=" + write;

                    ajaxWObj.open("GET", URL, true);
                    ajaxWObj.send(null);

                }
        }

</script>

The content of this script is one function, writin(), for writing, but without the ending g. This function checks if the client is writing by checking if the Text Area element has any content at all. This function is called every 10 seconds by the timeIntervalfn() function above, which itself is called every 10 seconds by a timer interval predefined function.

Remember, each time the client message is read, the Text Area is cleared. So, if there is any content in it, it means the client is typing (writing). This is checked every 10 seconds and if there is content (text), the Ajax function sends the information to the server database. It sends “writing=Yes” to the file, clientWriting.pl at the server for every 10 second instant that it finds text in the Text Area element. Read the above script to appreciate how the client typing (writing) is detected and sent. When there is no text nothing is sent; however, checking takes place every 10 seconds.

Corresponding Server Scripts
Each of the three large ECMAScripts above deals with a particular Perl script at the server. I discuss the operator server scripts in the next part of the series.

Operator Web Code
The code for the operator web page is similar to all the above. The operator web page has some differences. When the client fills the form (first document) at the client side and sends, at the operator page (side), an alert box signals the operator of this, indicating to the operator, the first name of the client. When the operator dismisses the alert box, the operator can then send his first message. The Text Area for the operator web page, is never disabled. It is the operator who sends the first message. The operator web page also has an End Conversation Button. When this button is clicked, the tables (chartMonitor and discussion) in the server database are erased (dropped). After ending the conversation, the operator sees an alert box, which indicates to him that he can begin a new conversation as soon as there is a new client. These difference features give the difference in code in the operator web page.

It will be boring to explain the functioning of the operator web page, as most of its code is similar to the one above. So I do not explain that in this series. At the end of the series, you will have the complete code for all the pages, scripts and database.

Time to take a break. We stop here and continue in the next part of the series.

Chrys

Related Links

Web Development Basics with Perl and MySQL
Perl Validation of HTML Form Data
Page Views with Ajax and Perl and MySQL
Web Live Text Chart Application using Perl and MySQL
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Follower
Send the Writer a Message