Web Technologies/2021-2022/Laboratory 6

JavaScript
JavaScript (JS) is an implementation of the ECMAScript standard, which is a scripting language based on the concept of prototype based programming. It is associated with Netscape Communications Corporation's and Mozilla’s foundation. is also used to The language is well known for its use in websites, as client side JavaScript. It can also enable scripting access to objects embedded in other applications.

IMPORTANT: JavaScript is not Java!

JS can perform a number of tasks; some the most important are:


 * doing browser detection
 * handling cookies
 * controlling browsers
 * validating forms
 * setting CSS properties dynamically, for example: element.style.border="1px solid black" (more examples at https://www.w3schools.com/html/html_css.asp)

JS code can be placed:


 * inside a   tag:

Insight on JS:
 * in a different page and then you can refer function in that file from within the HTML page:


 * has a syntax that is very similar with the one of Java and C. Therefore programmers used to write programs in those languages will get used with it easily.
 * IS case sensitive
 * has 3 types of pop up windows: alerts, confirms and prompts.
 * alert("MessageText") - displays a popup with an alert and an OK button
 * confirm("ConfirmText") - displays a popup and 2 buttons OK and Cancel. It returns a boolean value, depending on the button which was clicked
 * prompt("InfoText","defaultValue") - prompts the user to enter a value in a text field. It returns the entered value
 * if-else and loop statements are like the ones in C and Java
 * functions and events:


 * browser detection and managing:
 * In order to find out information about your browser you need to use the navigator object with the following properties:
 * navigator.appCodeName – stores the codename of the browser
 * navigator.appName – stores the name of the browser
 * navigator.appVersion – stores the browser version
 * navigator.userAgent – stores the header information for the browser
 * navigator.platform – stores the platform on which the browser is been run


 * cookies are stored in the document.cookie (although it seems to act as a string it isn't!) property of the document object. Cookies are client side variables that keep information about a site, such as last visit, user name, IP address etc. In order to use them, one needs to allow cookies in your browser. Basically a cookie has the following form: cookieName=cookieValue; expires=Thu, 01-Jan-2010 00:00:01 GMT;. The document.cookie variable contains a string in the form cookieName1=cookieValue1; cookieName2=cookieValue2. All a programmer should do is to write down 3 simple functions that manage cookies: setCookie(...), delCookie(...) and getCookie(...):


 * form validation works most of the times as follows:
 * the user enters some values in the form fields
 * when clicking the submit, an onsubmit (attached to the form tag) event is called which triggers the execution of a javascript that return either true (when validation is successful) or false (otherwise): onsubmit="return validateFields"

The JS (in our case validateFields function), will check each value entered in the fields that need validation. It checks field by field and if one does not check it simply add something to an error string (or only puts a boolean variable called isValid to false). When all fields are checked it looks to see if the error string is empty (no validation errors) and returns true. If not, it displays an alert showing that error string, and return false. (or, if using a boolean variable it simply returns that variable’s value).

The following example shows how we could use DOM to validate an email field inside a form: The echeck function is defined as follows: IMPORTANT: DOM is the preferred way of validating (X)HTML forms!

NOTE: to refer to the HTML document using DOM use the document keyword: NOTE: you can convert the DOM tree to string using: var domToString = document.getElementsByTagName('body')[0].innerHTML;. This method is useful if you want to send your modified HTML/XML DOM to the server for saving.

NOTE: in IE you can save the DOM using: IMPORTANT: however saving files locally is a security breach. This method is not 100% trusted or allowed by IE.

AJAX
AJAX stands for Asynchronous JavaScript and XML, and it combines several technologies:


 * XHTML and CSS for marking up and styling information
 * The DOM accessed with a client-side scripting language especially ECMAScript implementations suh as JavaScript and Jscript, to dynamically display and interact with the information presented
 * XML is sometimes used as the format for transferring data between server and client
 * XMLHttpRequest object, used to exchange data asynchronously

NOTE: AJAX is (the preferred way) a good choice of handling incoming data from the server

The following code fragment shows how we can create a simple AJAX application which reads an XML from the server:

You can also find more details here.

IMPORTANT: JS does not allow users to access local files (read/write) due to security issues (eg. viruses, trojans, etc.) so accessing a local file with an address other than starting with http:// is difficult.

NOTE: When you access local files be sure to add httpRequest.status = 0 besides 200 as there is no response status value from local files accessed without using a web server.

The XMLHttpRequest object doesn't just provide a way to register a callback for the handling of the readystate change (onreadystatechange). It also lets you define callbacks for:


 * progress notification - onprogress
 * page loading - onload
 * page error - onerror

Other useful functions are:


 * overrideMimeType - to force the change of a document's MIME-TYPE
 * setRequestHeader - sets the request HTTP header before sending it
 * getResponseHeader - gets the header of the response sent by the server
 * responseText - gets the response as plain text
 * responseXML - gets the response as XML

Given the previous code for asynchronously reading an XML we can write the following code for pre-loading and XML containing images:


 * XML file:


 * JS code:

Links:


 * AJAX
 * Mozilla AJAX howto
 * Sun AJAX howto
 * Wiki AJAX
 * W3Schools AJAX tutorial


 * DOM
 * W3 Schools DOM
 * W3 DOM

JSON
JavaScript Object Notation (JSON) is a a text based lightweight computer data interchange format similar to XML and aimed at replacing it inside browsers.

JSON objects are represented as follows:

Data is expressed as a pair of name:value list separated by commas: Arrays are expressed in the same way only that elements are placed inside square brackets: The XML for the previous JSON looks like the following: Accessing JSON data is straightforward. Several methods exist:


 * direct access:


 * using the eval function:


 * using the parse function:

NOTE: parse only works with browsers newer then Firefox 3.5 and IE 8.0. For older versions use one of the scripts found at http://json.org/. For a comparison amongst them see http://code.google.com/p/json-sans-eval/. However when using them be sure to pass a string as argument to the function.

IMPORTANT: using parse to handle JSON this method is the preferred one! eval should only be used to parse JSON if the source of the JSON-formatted text is completely trusted as it CAN execute ANY JS code and thus provides great security holes.

Executing JSON code received using AJAX is trivial as the following code shows. The onreadystatechange function described earlier remains the same and all we add is the parse function for executing JSON code:

Links:


 * JSON
 * JSON tutorial for JS
 * Python JSON module
 * Maven libraries -- JSON in JAVA

JSON vs XML
The debate over whether to chose JSON instead of XML is similar to that of choosing between PNG and JPG images in which developers of image-display applications decide their applications will handle one or the other. So it really comes down to a matter of scope and choice.


 * JSON is basically XML but with brackets instead of tags
 * They are Turing equivalent
 * JSON is basically serialized JS, XML is not and will (never) be
 * JSON is built for representing data structures whereas XML is built for giving semantic meaning to the text within documents
 * Every protocol i.e. SOAP. HTTP-POST, REST could be marshalled in JSON for faster processing
 * JSON is possibly better suited for client side processing
 * XML files are usually bigger while JSON is smaller due to its data interchange orientation

Links:


 * http://ajaxian.com/archives/json-vs-xml-the-debate

= Exercises =


 * Validate ALL the fields inside the forms created for Laboratory_2 using JS and DOM. For example validate numeric fields to be numeric and also to be in the correct range i.e. between 0 and 100 for example;
 * You can use the "Try it Yourself!" section from http://www.w3schools.com/js/tryit.asp?filename=tryjs_validation_js.
 * For further details please consult http://www.w3schools.com/js/js_intro.asp
 * Lab 2 sample

Homework
Gabriel Iuhasz, 2019-11-05, [mailto:iuhasz.gabriel@e-uvt.ro iuhasz.gabriel@e-uvt.ro]
 * Create a simple HTML page which loads several imagines inside a table with no borders using JS and AJAX. The locations of the images will be read from a JSON/XML based input. Use DOM to create the table.
 * Helper function for creating tables from JS

Alexandru Munteanu, 2021-11-01, [mailto:alexandru.munteanu@e-uvt.ro alexandru.munteanu@e-uvt.ro]