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
1.1. Embedding Client-Side Scripts
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
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:
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.”
2.1. Using Server-Side Script with AJAX
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.