Broad Network

Bringing in more Gallery Items to the Browser, using the EMySQL API

Web Development Basics with ECMAScript and MySQL – Part 9

Web Development with ECMAScript and MySQL in Node.js

Foreword: In this part of the series, I explain how to bring in more gallery items to the browser, using the Pure ECMAScript MySQL API, in web development.

By: Chrysanthus Date Published: 17 Jul 2016


This is part 9 of my series, Web Development Basics with ECMAScript and MySQL. In this part of the series, I explain how to bring in more gallery items to the browser, using the Pure ECMAScript MySQL API, in web development. I assume you have read the previous parts of the series, before reaching here; this is a continuation.

Coding of Items at the Browser
In one of the previous parts of the series, I said that there would be 4 hard coded book items in the books page. I also said that there would be 4 hard coded pen items in the pens page. This is how it should be in order to make the site, search engine friendly. The items hard coded on a page, are the first 4 items in a category of the products table.

Here is the table code for the bookshop page.

    <table id="B1">
            <tr><td><img src='itemsDir/BookA.jpg' onclick="openWin(0)"><br>Book A Title<br>This book written by ... published by ... year... explains ...</td><td><img src='itemsDir/BookB.jpg' onclick="openWin(1)"><br>Book B Title<br>This book written by ... published by ... year... explains ...</td></tr>
            <tr><td><img src='itemsDir/BookC.jpg' onclick="openWin(2)"><br>Book C Title<br>This book written by ... published by ... year... explains ...</td><td><img src='itemsDir/BookD.jpg' onclick="openWin(3)"><br>Book D Title<br>This book written by ... published by ... year... explains ...</td></tr>

The table for the pens is similar. I have added more code here than the one you saw in one of the previous parts of the series. The table now has an ID (you will see its use soon). Each image in a cell has the onclick event. The onclick event attribute calls a function, passing a number as argument. The left-top cell has the index number 0, the right-top cell has the index number 1; the left-bottom cell has the index number 2 and the right-bottom cell has the index number 3. These numbers correspond to the numbers in an array that holds the item details (explanation) at the browser web page. Remember, an item has a name (title in the case of a book), a short summary and explanation. The explanation is the detail. The explanation for each item is in the cell of the array. You, the coder, has to type out this array, and feed it with the explanations (details).
In the above table, you have the name of item, and short summary for the item. The following ECMAScript can be used to create the array and feed it with data at the web page:

<script type="text/ECMAScript">

    itemArr = new Array();
    itemArr.push("Details 0…", "Details 1…", "Details 2…", "Details 3…");


The array variable is at the global level. This ECMAScript has to be hard coded. The push method will actually be something like:

    itemArr.push("Details 0…", "Details 1…", "Details 2…", "Details 3…", "dummy" );

The last cell value will not be used at the browser. It is there to make the coding of the corresponding ECMAScript file simple (see below).

The onclick Event
The function called by the onclick event is, openWin(indx). The function opens a new window, displaying the image that was clicked at its full size. The window also displays the name of the item, the short summary of the item and the explanation (details) of the item. The name and short summary of the item are taken from the corresponding cell of the table. The explanation is taken from the array.

The open window will have an input number control, where the user can type in the number of the particular item he wants. The opened window will also have two buttons: One button would send the user’s decision of buying the item to the shopping cart; the other button will cancel the operation of choosing and buying the item. You will see how this window is coded later in the series.

The style sheet of the books or pens page has the following line:

        img {width:200px;height:200px}

This line forces any image in its page to be 200px X 200px. The images are actually 400px X 400px. So, if an image tag is copied to the opened window, it will appear at its normal (big) 400px X 400px size. The opened window does not have any style sheet. In practice, the size in the books and pens page may be, 100px;height:100px.

The More Hyperlink
Below the table that has the items for sale, is this hyECMAScriptink:

    <a href= "more.js?maxNum=4"><strong>More . . .</strong></a>

When this hyperlink is clicked, the ECMAScript file named, “more.js” at the web server is executed (called). This file will read 4 more items from the database and send them in a new web page document to the browser. As seen from the href value above, this ECMAScript file at the server, receives the number, 4, as the 'maxNum' value of the CGI. This number is the maximum position item number on an item (books or pen) web page. At the moment it is 4 because the number of items is 4. When the new page has been received at the browser, this number would be 8 (i.e. 4+4), but the page will display only the 4 new items. If there were more than 8 category items in the database, then the next number would be 12 (8+4). The items are sent from the server to the browser in groups of 4. In a commercial project it should be at least, groups of 16. In order for the “more.js” script to know the next category item number from which it should pull the next 4 items from the database, it adds 1 to the number of the href value above. You will see how the number in the href value is determined, shortly.

You should now modify the “books.htm” and “pens.htm” files with the above table and above hyperlink (copy and paste).

What is sent back to the Browser
When the More hyECMAScriptink in the web page is clicked, the “more.js” file in the web server is executed (called). The function of the file is to send the next 4 items in the category from the products table to the browser, in a new page. We see how this is done in this part of the series.

Now, the web page sent to the browser needs to have the features of the items page (books or pens page). The things that can change are the page title and the data; the “more.js” file is responsible for sending the new books page or the new pens page, to the browser. This ECMAScript file has to send the document to the browser in 5 portions. The first portion is code for the items page (books.htm or pens.htm), from the top to the title. After that the file should send the “Books in University Bookshop” or “Pens in University Bookshop” title text; that is the second portion. Then the ECMAScript file should send the code beginning from the title to the items table top; that is the third portion. After that it sends the fourth portion, which is the data from the database. These data will be displayed as the 4 items (images and text). Then it sends the last (fifth) portion, which is code from the items table, to end of page (</html>). The ECMAScript file does all this, for the books page or the pens page.

This ECMAScript file actually builds a books page or pens page. However, what it sends is ECMAScript page and not an HTML page, even thought all the code sent to the browser, ends up as HTML. When this is done, at the browser, if you look in the address bar, you would notice that the extension of the file of the page displayed is, pl (and not htm or html). Such a page never existed and had to be created by the ECMAScript script (file) at the server. Such a page cannot be seen by search engines.

Now, in order for the ECMAScript file to know whether it is to send the books title and books data or the pens title and pens data, you have to modify the hyECMAScriptink in the item page. If the items page is “books.htm” then the hyECMAScriptink would be:

    <a href= "more.js?maxNum=4&category=books"><strong>More . . .</strong></a>

Note the new value (books) of the href attribute. If the items page is “pens.htm” then the hyECMAScriptink would be:

    <a href= "more.js?maxNum=4&category=pens"><strong>More . . .</strong></a>

Note the new value (pens) of the href attribute.

Go ahead and make this modification in the books and pens HTML page (as you carry out the project).

The more.js File
This file is at the server.

The First Code Segment
The first code segment is:

const mysql = require('./Mysql.js');

This includes the MySQL API. Below that you have the function,

exports.more = function(url, callback)


The rest of the code segments are in the body of this function.

The Second Code segment
It is:

        url = decodeURIComponent(url);
        url = url.replace(/\+/g, " ");
        queryStr = url.replace(/^.*\?/g, "");

The node server sends the URL of the more hyperlink to this file and not the form data bytes.

This code segment extracts the query part (after ?) of the URL and place into the variable, queryStr.

The Third Code Segment
It is:

        keyValueArr = queryStr.split('&');

        keyValueMap = new Map();
        for (item of keyValueArr )
                arr = item.split('=');
                keyValueMap.set(arr[0], arr[1]);

        maxNum = keyValueMap.get('maxNum');
        category = keyValueMap.get('category');

        //validation should be done here.

This code segment places the name/value pairs of body into a map of key/value pairs. It then assigns values of key/value pairs from the map to variables (names).

The Fourth Code segment
This segment retrieves product features from the database and sends as a new web page to the client. It logs into the database as root, for simplicity, but it should log as the user.

The segment defines callback functions that are called from the MySQL module. The segment also calls the callback function defined in the node server process (for feedback to the client).

The code segment is:

        var feedback;

        //Page Variables
        var topPage;
        var articleContent;
        var clientSriptAndBottom;

        //prepare the top of the page
        topPage = `<!DOCTYPE HTML>
            <title>Books in University Bookshop</title>
            <style type=\"text/css\">
                img {width:200px;height:200px}
        <h1>University Bookshop</h1>
        <a href='index.htm'>Home</a> <a href='books.htm'>Books</a> <a href='pens.htm'>Pens</a> <a href='login-registration.htm' id=\"login\">Login</a> <a href='login-registration.htm#register'>Register</a>
            <table id=\"B1\">

        //deal with database
        con = new mysql.Connection("root", "secret", "localhost", 3306, function (err)
                if (err)
                        feedback = "Connection to database could not be made. See web master";

        //select database
        con.query("USE BookShop", function(err, Result)
                if (err)
                        error = "Database could not be selected. See webmaster.";

        //format data with HTML tags and assign to variable
        var startCategoryItemNo = Number(maxNum) + 1; //because of what is recorded in database
        var endCategoryItemNo = Number(maxNum) + 4;
        var explanation;
        var loopCounter = 1;

        var productsSlct = `select productName, price, imageFileName, imageDir, shortSummary, explanation FROM Products WHERE category=\"Book\" AND categoryItemNo >= '${startCategoryItemNo}' AND categoryItemNo <= '${endCategoryItemNo}'`;
        con.query(productsSlct, function(err, Result){
            if (err)
                    error = "Could not select product features. See webmaster.";
                    for (i=0; i<Result.length; ++i)
                            var openWinNum = loopCounter - 1;

                            if ((loopCounter % 2) == 1)
                                    articleContent += "<tr><td><img src=";
                                    articleContent += "\"" + Result[i].get("imageDir") + "/" + Result[i].get("imageFileName") + "\"";
                                    articleContent += ` onclick=\"openWin(${openWinNum})\"><br>`;
                                    articleContent += Result[i].get("productName") + " Price: \$" + Result[i].get("price") + "<br>";
                                    articleContent += Result[i].get("shortSummary") + "<br>";

                                    explanation += "\"" + Result[i].get("explanation") + "\",";

                                    articleContent += "</td>";     
                                    articleContent += "<td><img src=";
                                    articleContent += "\"" + Result[i].get("imageDir") + "/" + Result[i].get("imageFileName") + "\"";
                                    articleContent += " onclick=\"openWin(${openWinNum})\"><br>";
                                    articleContent += Result[i].get("productName") + " Price: \$" + Result[i].get("price") + "<br>";
                                    articleContent += Result[i].get("shortSummary") + "<br>";
                                    explanation += "\"" + Result[i].get("explanation") + "\",";
                                    articleContent += "</td></tr>";  

                            loopCounter += 1;

                        explanation += "\"dummy\"";

                        clientSriptAndBottom = `        </tbody>
                             <a href= \"more.js?maxNum=${endCategoryItemNo}&category=books\"><strong>More . . .</strong></a>
                               <script type=\"text/ECMAScript\">
                                 itemsArr = new Array();


                           <script type=\"text/ecmascript\">
                             if (sessionStorage.login == \"login\")
                                   document.getElementById('login').href = \"logout.htm\";
                                   document.getElementById('login').textContent = \"Logout\";


                            if (feedback == undefined)
                                    page = topPage + articleContent + clientSriptAndBottom;

                                    callback(null, page);
                                    callback(null, 'Could not login!');


To test the scheme, you have to type the following in the address bar of the browser and click Go.


You can then click the More… Button.

We have had a long ride for this tutorial. We really have to take a break now. We continue in the next part of the series.


Related Links

Web Development Basics with ECMAScript and MySQL
ECMAScript Validation of HTML Form Data
Web Live Text Chart Application using ECMAScript and MySQL
More Related Links
Node Mailsend
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course



Become the Writer's Follower
Send the Writer a Message