Using Scripting Languages with HTML

Scripting languages are essential to the development of Web applications. Although simple Websites that offer just links between pages can be accomplished with just HTML and CSS, complex sites that require interactivity as well as data to be processed and stored require the use of scripting languages. Scripts can be written for client-side or server-side execution. Client-side execution is done by the browser and server-side execution is done by the server. Scripting, which is programming, is much more complex than writing HTML or CSS. To learn specific scripting languages, you can use any of the many books available in the market or Web tutorial sites. Here, only how to use these scripts with HTML is discussed.

1. Client-Side Scripting

Client-side scripting was developed to prevent the Web browser from having to contact the Web server each time a user performs an action on a page. This is because such action inevitably results in the reloading of a Web page, which is inefficient. For example, it gives the server extra work and uses excessive bandwidth. It also produces poor user- experience (e.g., all page-content disappears and reappears each time). Although client- side scripting can be done in different languages, JavaScript is the most commonly used. Like CSS, scripts can be embedded in HTML code or written in a separate file to which the HTML can be linked. Embedded client-side scripts can be viewed by users the same way that ordinary HTML codes can, usually via the “View” menu in Internet Explorer and Safari, or via mouse-right- button context menu in Firefox and Chrome. Users cannot view external scripts.

1.1. Embedding Client-Side Scripts

When embedding a script in HTML, the script is placed inside the <script> element, which is placed in the <head> or <body> element. Either way, the Web browser is able to execute it. Figure 22.3 shows a JavaScript placed in the <body> element. The type attribute is used to specify in which language the script is written. This is known as the MIME type. Although it is not mandatory to include this for JavaScript, it is good practice to ensure certainty. The script in the example writes “Hello World!” when the <body> element loads (i.e., when the HTML document loads). The JavaScript statement more or less speaks for itself; the document is an object, whose write method is used to display “Hello World” on the screen. The <noscript> element is used to provide a message to users using browsers that do not support JavaScript or who have JavaScript turned off.

When scripts are embedded in the <head> element, they are usually in the form of functions (sub-routines), which are then called from within the <body> element. Figure 22.4 shows an example that does the same thing that the code in Figure 22.3 does. The function, message(), is declared when the <head> element is loaded and called when the <body> element is loaded, using onload=message() statement. In essence, the statement says when the <body> element loads, to execute the function called message (). The onload attribute is known as a global event attribute. As mentioned in Chapter 2, a global event attribute is generated by any element.

1.2. External Client-Side Scripts

As in external CSS, external client-side scripts are typically linked to by a single line of statement in the HTML document. Again, this line can be placed in the <head> or <body> element. The same rationale behind using external CSS instead of embedded CSS applies to using external scripts—they can be shared by more than one HTML document, making maintenance easier. Figures 22.5 and 22.6 show where the line that links to an external script is placed and how the functions in the script are called for execution. The script, in this case, “test.js,” can be placed in the same folder as the associated HTML document in the Web server or in a sub-folder typically named “scripts” inside the folder containing the HTML document. When the browser sees the src attribute in the <script> element, it includes all the JavaScript in the specified file inside the element, as in Figure 22.4. Assuming the test.js script contains the same message() function (again shown in Figure 22.4), the function is called upon the loading of the page.

Instead of spending time writing JavaScript codes, a common practice is to use JavaScript libraries, which provide prewritten codes and are available from various sources on the Web. One of the most popular libraries is the jQuery library. It is a single long JavaScript file that contains codes for common functionalities and available in two versions (“jquery. js” and “jquery.min.js”) at various online sites to link to or download. The two versions contain essentially the same codes. The former contains the long version of the codes and jquery.min.js the minified version. The minified version has the elements that are unnecessary for functioning (e.g., whitespace and comments), stripped out, and variable names shortened, thereby minimizing size and loading time for the file, making it more suitable for production environments where optimized performance is required. However, it is more difficult to read for the same reasons. So, jqueryjs is typically used during development when it may be necessary to look in the file for helpful comments on usage.

To use the jQuery library, it is either downloaded into a folder and referenced locally, in which case “jqueryjs” or “jquery.min.js” is assigned to the src attribute of the <script> element, or it may be referenced directly on any of the many Content Delivery Networks (CDNs), such as Google and Microsoft, that host it on their server, in which case the relevant URL is assigned to the src attribute. The following line, for example, links to the minified version 1.10.2 on Google’s host server:

src=“http://ajax.googleapis.com/ajax/libs/jquery/L10.2/jquery.minjs”

Once the library is linked to, any function in it can be used, using jQuery syntax, which is much easier to use and less wordy than JavaScript. For example, the JavaScript code in Figure 22.7 produces the same result as the jQuery in Figure 22.8. Notice that what is achieved with about four lines of JavaScript code is achieved with only one line of jQuery code. The codes essentially say to make the background of the Web page gray when the button is clicked. In the jQuery, the $, which is used to select HTML elements, is used to select the <body> element, after which css is used to assign “gray” color to its background.

2. Server-Side Scripting

Trying out the examples in this section requires a client-server setup. If you want to try them out, you need to install a server on your computer. There are many free ones on the Web. A common one is WampServer. Download and install the version compatible with your system. If the installation is successful, an icon should be placed on the taskbar. Click it and then click “Put Online” on the menu, if the server is not already online. If WampServer is not running, start it (e.g., from the Desktop) and then put it online as described above. The initial aim is to ensure that the environment is correctly set up to run both HTML and server-side scripts, in this case, PHP scripts. To do this, create a php folder in the www folder that is in the wamp folder created during installation. Next, create the PHP script in Figure 22.9, name it “hello.php,” and then place it in the PHP folder. To test if the setup is working, type the following URL in the Web browser’s address window: http://localhost/ hello.php. If the setup is working properly, “Hello World!” should be displayed. This means that the PHP script in the server was executed. Now you can try out the rest of the examples in this chapter, if you want to, and many others from the Web.

Like client-side scripts, server-side scripts can be written in one of various languages, including C++, PHP, Python, and Ruby. The way it works (which was generally illustrated in Figure 1.3 in Chapter 1) is that when a Web page requests a server-side script, the server fetches it, executes it, and then sends the output to the Web client, usually in HTML. The output may also contain client-side scripts. Like client-side scripts, server-side scripts can either be embedded or be in a separate file. However, when they are embedded in HTML, the resulting document is not referred to as an HTML document and therefore does not have the .html extension but the extension of the language used, such as .php for PHP. Figure 22.9 shows PHP embedded in HTML and Figure 22.10 the HTML document outputted and sent to the browser by the server. The <?php.. .?> specifies that the line is a PHP statement and echo is a PHP command for outputting content; in this case it outputs “Hello World.”

One of the functions that server-side scripts are used for is processing the data collected with a form. Typically, processing would involve, for example, storing the data in a database or using it to retrieve relevant data from the database and sending the retrieved data to the browser. Figures 22.11 and 22.12 show an example of how an HTML form and a server-side PHP script work together.

In the example, the form requires a user to type in their name and age. It also specifies that the script to use to process the data is “personal.php” and that it is situated in the php folder. When the submit button is pressed on the form, the data are packaged and sent to the Web server through the POST method where the specified server-side script is used to process the data. The script, in this case, simply extracts each of the form data, name, and age, and stores them in variables $name and $age, respectively, after which it outputs “Hi,” plus a space, plus the content of $name, then a paragraph, and then “You are,” plus a space, plus the content of $age, plus a space, plus “years old,” after which it sends everything to the browser. So, assuming “Joe” and “35” are inputted for name and age on the form, respectively, the script returns “Hi Joe” “You are 35 years old.”

If the data are to be stored in a database, then the script will open one and insert them as necessary. If the data are to be used to retrieve data from a database, then, similarly, the script opens one and uses the data to search for matches, which are then sent to the browser. Examples of the general principles that guide these operations are presented shortly. As mentioned in Chapter 5, to ensure that correct data are sent to the server in the first place, it is normal and good practice to validate them (using HTML or JavaScript) before submitting a form. All these and more are typical processes required for Web applications that collect user-data, which include e-commerce and social sites.

2.1. Using Server-Side Script with AJAX

Traditionally, the way the data that are sent to the Web browser by the Web server is displayed is to replace the whole of the current page with a new one containing the sent data, even if only a small part of the current page needs to be updated with the data. This is inefficient and inconvenient. To address this issue, a more efficient technology known as Asynchronous JavaScript and XML (AJAX) has since been developed that allows Web applications to communicate with a server asynchronously. Basically, it allows data to be sent to and retrieved from a server in the background, without refreshing the current page or interfering with its current state in any way. The framework combines JavaScript with various Web technologies, both existing ones and new ones. Central to the asynchronous communication process is a special JavaScript object called XMLHttpRequest, which is used to send data to a server as well as receive data from it. To cater to older Internet Explorer browsers, the object may also be called ActiveXObject. A basic example of how AJAX is used with HTML is presented in Figures 22.13 and 22.14, in which a form containing a single text field and a button is displayed. Clicking the button displays the current server time both in the text field and in an alert box, just to demonstrate more than one usage.

In the example, a function, named ajaxFunction(), is defined that is called when the button on the form is clicked. In the function, a new instance of the XMLHttpRequest object is created and named ajaxRequest. An object is a self-contained piece of data that comprises its own set of properties (which can be changed or retrieved) and methods (which are actions it can perform, either automatically or as a result of being instructed to perform them). The open() method of the ajaxRequest object specifies via its three parameters to (1) send the form request to the server via the GET method, (2) use the specified script to process the request, and (3) handle the request asynchronously. The send() method sends the request.

When the request is sent to the server, the onreadystatechange event is triggered in the ajaxRequest object when the status of its readyState property changes. The example says when the onreadystatechange event is triggered, and if the status of the readyState property is “4” (i.e., if the server’s response to request is completed), to assign the content of the responseText property of the ajaxRequest object to the value attribute of the HTML element named “time,” which is in the form named “dataForm” (which is the form that sent the request). The result is that when the form button is clicked, the ajaxFunction() is called and a request sent to the server, which executes the serverTime.php script in Figure 22.14, which returns the server’s current time, which is sent to the browser and stored in the responseText property, which is assigned to the value attribute of the <input> element named “time” in the form named “dataForm.” Assigning the returned time to the value attribute automatically displays it in the text field. Also, the alert. () method displays the time (content of responseText) in an alert box. All this is done without reloading the page or changing anything else on it.

2.2. Server-Side Script, AJAX, and Database

As mentioned earlier, server-side scripting is central to storing data in or retrieving them from a database, while a database is central to any Web application that stores information. Databases come in various genre, such as relational, object-oriented, and NoSQL, just as there are many implementations of each genre. One of the most commonly used open- source software database systems is MySQL and it is the one used for demonstration here. It is a relational database system, which in basic terms means it is a system of databases that contain collections of tables that can be interlinked through their columns. So, a database contains many tables, each of which is used to store data in an organized way, any of which may be linked to produce a cohesive report. For example, a database called “A_Company” might contain a table called “Customer” that stores customers’ details, another, “Order,” that stores their current orders, and another, “Transactions,” that stores the completed orders, and so on. From such a database, server- side scripting can be used to generate a report, for example, to list all customers and the outstanding and completed orders for each.

In all cases, when writing data to or reading data from a database, the typical procedure is to first connect to the database, open it, and then query the relevant tables, using statements written, for example, in a special language known as Structured Query Language (SQL). Again, AJAX can be used to send and receive data retrieved from a database.

2.3. Storing Data in Database

Figures 22.15 and 22.16 show a basic example for collecting data with an HTML form, packaging and sending it to the server using AJAX, and storing it in a MySQL database using server-side scripting.

In Figure 22.15, a form is displayed that requires the user to enter username, password, and postcode. When the submit button is clicked, the ajaxFunction() is called to package and send the data to the server. In the a j axFunc t ion (), as in the previous example, a new instance of the XMLHttpRequest is created and named ajaxRequest. The data entered in the input fields by the user are then stored in variables, respectively, and a string of name-value pairs constructed with them and placed in another variable. The open() method specifies via its three parameters to (1) send the form data to the server via the GET method, (2) use the specified script (storeData.php) to process the data, and (3) handle communication with the server asynchronously. The send() method submits the form data to the server.

Once the form data gets to server, the storeData.php script connects to the database and opens it for use, after which the code for querying it (the SQL statement) is built. The code is used to query a table called “users” in the database, which contains columns (or fields) named username, password, and postcode. Essentially, when the SQL statement is executed, the values of $uname, $pword, and $pcode (i.e., data from the form) are inserted in the next new row in the table.

2.4. Retrieving Data from Database

Figures 22.17 and 22.18 show a basic example of collecting data with an HTML form, packaging and sending it to the server with AJAX, using it to search a database, and returning the result, using server-side scripting.

Figure 22.17 displays a form that consists of a field for the user to enter a postcode, a submit button, and the text “Records are listed here” under it. Where the text is placed is where the result of the search of the database will be displayed. As in the previous example, when the submit button is clicked, the ajaxFunction() function is called to package and send the inputted data to the server. The ajaxFunction() function creates a new instance of the XMLHttpRequest object and names it ajaxRequest. It then places the postcode data from the form in a variable (pcode), creates a name-value pair with it, and stores in another variable (qString). The open() method says to send the data via the POST method, process it with the script called retrieveRecords.php, and use asynchronous communication. The setRequestHeader() method adds an HTTP header to the request to set its content type to “application/x www form-urlencoded, ” which is the default content type for a POST request and required for a POST request via AJAX. The send() sends the data to the server.

On the server-side, the posted data are passed to retrieved_Records.php (the script in Figure 22.18), which opens the relevant database (zzforum), isolates the postcode, and uses it to search the “users” table in the database for record that match it, using the mysql _ query () function. If any matches are found, the records are stored in query-result variable. A table is then constructed with the data of the records, stored in the record_string variable, and outputted to the browser, where it is stored in the ajaxRequest.responseText property of the ajaxRequest object. Once the onreadystatechange event of the object is fired to indicate that the status of the readyState property has changed and the response from the server is completed, the content of ajaxRequest.responseText is placed in the <div> element of id=“listRecords”, which automatically displays it. The innerHTML is a property that is used to access the text between the tags of an HTML element.

Source: Sklar David (2016), HTML: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *