Introduction to Dynamic Web Programming with AngularJS, JavaScript, and jQuery
- Understanding the Web Server/Browser Paradigm
- Setting Up a Web Development Environment
- Summary
- Q&A
- Workshop
JavaScript and its amped-up companions, jQuery and AngularJS, have completely changed the game when it comes to creating rich interactive web pages and web-based applications. JavaScript has long been a critical component for creating dynamic web pages. Now, with the advancements in the jQuery and AngularJS libraries, web development has changed forever.
This lesson quickly takes you through the world of jQuery and JavaScript development. The best place to start is to ensure that you understand the dynamic web development playground that you will be playing in. To be effective in JavaScript and jQuery, you need a fairly decent understanding of web server and web browser interaction, as well as HTML and CSS.
This lesson includes several sections that briefly give a high-level overview of web server and browser interactions and the technologies that are involved. The rest of this lesson is dedicated to setting up and configuring an AngularJS, jQuery, and JavaScript friendly development environment. You end with writing your very first web pages that include JavaScript and jQuery code.
Understanding the Web Server/Browser Paradigm
JavaScript, jQuery, and AngularJS can interact with every major component involved in communication between the web server and the browser. To help you understand that interaction better, this section provides a high-level overview of the concepts and technologies involved in web server/browser communication. This is not intended to be comprehensive by any means; it’s simply a high-level overview that enables you to put things into the correct context as they are discussed later in the book.
Looking at Web Server to Browser Communication Terms
The World Wide Web’s basic concept should be very familiar to you: An address is typed into or clicked in a web browser, and information is loaded and displayed in a form ready to be used. The browser sends a request, the server sends a response, and the browser displays it to the user.
Although the concept is simple, several steps must take place for the data to be requested from the server and displayed in the browser. The following sections define the components involved, their interactions with each other, and how JavaScript, jQuery, and AngularJS are involved.
Web Server
The web server is the most critical component of the web. Without it, no data would be available at all. The web server responds to requests from browsers by sending data that the browsers then use or display. A lot of things happen on the web server, though. For example, the web server and its components check the format and validity of requests. They may also check for security to verify that the request is from an allowed user. To build the response, the server may interact with several components and even other remote servers to obtain the data necessary.
Browser
The next most important component is the browser. The browser sends requests to the web server and then displays the results for the user. The browser also has a lot of things happening under the hood. The browser has to parse the response from the server and then determine how to represent that to the user.
Although several browsers are available, the three most popular are Chrome, Internet Explorer, and Firefox. For the most part, each browser behaves the same when displaying web pages; however, occasionally some differences exist, and you will need to carefully test your JavaScript, jQuery, and AngularJS scripts in each of the major browsers that you are required to support.
JavaScript, jQuery, and AngularJS can be very involved in the interactions that occur between the browser receiving the response and the final output rendered for the user. These scripts can change the format, content, look, and behavior of the data returned from the server. The following sections describe important pieces provided by the browser.
DOM
The browser renders an HTML document into a web page by creating a Document Object Model, or DOM. The DOM is a tree structure of objects with the HTML document as the root object. The root can have several children, and those children can have several children. For example, a web page that contains a list would have a root object, with a child list object that contained several child list element objects. The following shows an example of simple DOM tree for a web page containing a single heading and a list of three cities:
document + html + body + h1 + text = "City List" + ul + li + text = "New York, US" + li + text = "Paris, FR" + li + text = "London, EN"
The browser knows how to display each node in the DOM and renders the web page by reading each node and drawing the appropriate pixels in the browser window. As you learn later, JavaScript, jQuery, and AngularJS enable you to interact directly with the DOM, reading each of the objects, changing those objects, and even removing and adding objects.
Browser Events
The browser tracks several events that are critical to AngularJS, jQuery, and JavaScript programs—for example, when a page is loaded, when you navigate away from a page, when the keyboard is pressed, mouse movements, and clicks. These events are available to JavaScript, allowing you to execute functionality based on which events occur and where they occur.
Browser Window
The browser also provides limited access to the browser window itself. This allows you to use JavaScript to determine the display size of the browser window and other important information that you can use to determine what your scripts will do.
URL
The browser is able to access files on the web server using a Uniform Resource Locator, or URL. A URL is a fully unique address to access data on the web server, which links the URL to a specific file or resource. The web server knows how to parse the URL to determine which file/resources to use to build the response for the browser. In some instances, you might need to use JavaScript to parse and build URLs, especially when dynamically linking to other web pages.
HTML/HTML5
Hypertext Markup Language, or HTML, provides the basic building blocks of a web page. HTML defines a set of elements representing content that is placed on the web page. These element tags are used to create objects in the DOM. Each element tag pair is represented as an object in the DOM. Each element is enclosed in a pair of tags denoted by the following syntax:
<tag>content</tag>
For example:
<p>This is an HTML paragraph.</p>.
The web browser knows how to render the content of each of the tags in the appropriate manner. For example, the tag <p> is used to denote a paragraph. The actual text that is displayed on the screen is the text between the <p> start tag and the </p> end tag.
The format, look, and feel of a web page is determined by placement and type of tags that are included in the HTML file. The browser reads the tags and then renders the content to the screen as defined.
HTML5 is the next generation of the HTML language that incorporates more media elements, such as audio and video. It also provides a rich selection of vector graphic tags that allow you to draw sharp, crisp images directly onto the web page using JavaScript.
Listing 1.1 shows an example of the HTML used to build a simple web page with a list of planets. The HTML is rendered by the browser into the output shown in Figure 1.1.
FIGURE 1.1 List of planets rendered in a browser using the code from Listing 1.1.
LISTING 1.1 list.html A Simple HTML Document That Illustrates the HTML Code Necessary to Render a List in a Browser
01 <!DOCTYPE html> 02 <html> 03 <head> 04 <title>Server Side Script</title> 05 <meta charset="utf-8"/> 06 </head> 07 <body> 08 <ul> 09 <li>Mercury</li> 10 <li>Venus</li> 11 <li>Earth</li> 12 <li>Mars</li> 13 </ul> 14 </body> 15 </html>
CSS/CSS3
One of the challenges with web pages is getting them to look sharp and professional. The generic look and feel that browsers provide by default is functional; however, it is a far cry from the sleek and sexy eye candy that users of today’s Internet have come to expect.
Cascading Style Sheets, or CSS, provide a way to easily define how the browser renders HTML elements. CSS can be used to define the layout as well as the look and feel of individual elements on a web page.
CSS3, or Cascading Style Sheets level 3, is the next generation of CSS that incorporates more special effects, such as transformations and animations. It also provides rich additions for borders, backgrounds, and text.
To illustrate CSS, we’ve added some CSS code to our example from Listing 1.1. Listing 1.2 uses CSS to modify several attributes of the list items, including the text alignment, font style, and changing the list bullet from a dot to a check-mark image. Notice how the CSS style changes how the list is rendered in Figure 1.2.
FIGURE 1.2 The CSS code dramatically changes the look of the list in the browser.
LISTING 1.2 style.htm HTML with Some CSS Code in <STYLE> Element to Alter the Appearance of the List
01 <!DOCTYPE html> 02 <html> 03 <head> 04 <title>Style</title> 05 <meta charset="utf-8" /> 06 <style> 07 li { 08 text-align: center; 09 font-family: "Times New Roman", Times, serif; 10 font-size: 30px; 11 font-style: italic; 12 font-weight: bold; 13 list-style-image: url('/images/check.png'); 14 list-style-position: inside; 15 } 16 </style> 17 </head> 18 <body> 19 <ul> 20 <li>Mercury</li> 21 <li>Venus</li> 22 <li>Earth</li> 23 <li>Mars</li> 24 </ul> 25 </body> 26 </html>
HTTP/HTTPS Protocols
Hypertext Transfer Protocol (HTTP) defines communication between the browser and the web server. It defines what types of requests can be made, as well as the format of those requests and the HTTP response.
Hypertext Transfer Protocol with Secure Sockets Layer (HTTPS) adds an additional security layer, SSL/TLS, to ensure secure connections. When a web browser connects to a web server via HTTPS, a certificate is provided to the browser. The user is then able to determine whether to accept the certificate. Without the certificate, the web server will not respond to the user’s requests, thus ensuring that the request is coming from a secured source.
The following sections discuss HTTP headers and the two most common types of HTTP request, GET and PUT.
HTTP Headers
HTTP headers allow the browser to define the behavior and format of requests made to the server and the response back to the web browser. HTTP headers are sent as part of an HTTP request and response. You can send HTTP requests to web servers from JavaScript, so you need to know a little bit about the headers required.
The web server reads the request headers and uses them to determine how to build a response for the browser. As part of the response, the web server includes response headers that tell the browser how to process the data in the response. The browser reads the headers first and uses the header values when handling the response and rendering the page.
Following are a few of the more common ones:
- ACCEPT—Defines content types that are acceptable in the response.
- AUTHORIZATION—Specifies authentication credentials used to authenticate the requesting user.
- COOKIE—Cookie value that was previously set in the browser by a server request. Cookies are key/value pairs that are stored on the client. They can be set via server requests or JavaScript code and are sent back to the server as part of HTTP requests from the browser.
- SET-COOKIE—Cookie value from the server that the browser should store if cookies are enabled.
- CONTENT-TYPE—Type of content contained in the response from the web server. For example, this field may be “text/plain” for text or “image/png” for a .png graphic.
- CONTENT-LENGTH—Amount of data that is included in the body of the request or response.
Many more headers are used in HTTP requests and responses, but the preceding list should give you a good idea of how they are used.
GET Request
The most common type of HTTP request is the GET request. The GET request is generally used to retrieve information from the web server—for example, to load a web page or retrieve images to display on a web page. The file to retrieve is specified in the URL that is typed into the browser, for example:
http://www.dayleycreations.com/tutorials.html
A GET request is composed entirely of headers with no body data. However, data can be passed to the server in a GET request using a query string. A query string is sent to the web server as part of the URL. The query string is formatted by specifying a ? character after the URL and then including a series of one or more key/value pairs separated by & characters using the following syntax:
URL?key=value&key=value&key=value...
For example, the following URL includes a query string that specifies a parameter gallery with a value of 01 that is sent to the server:
http://www.dayleycreations.com/gallery.html?gallery=01
POST Request
A POST request is different from a GET request in that there is no query string. Instead, any data that needs to be sent to the web server is encoded into the body of the request. POST request are generally used for requests that change the state of data on the web server. For example, a web form that adds a new user would send the information that was typed into the form to the server as part of the body of a POST.
Web Server and Client-Side Scripting
Originally, web pages were static, meaning that the file that was rendered by the browser was the exact file that was stored on the server. The problem is that when you try to build a modern website with user interactions, rich elements, and large data, the number of web pages needed to support the different static web pages is increased dramatically.
Rather than creating a web server full of static HTML files, it is better to use scripts that use data from the web server and dynamically build the HTML that is rendered in the browser.
Those scripts can run either on the server or in the client browser. The following sections discuss each of those methods. Most modern websites use a combination of server-side and client-side scripting.
Client-Side Scripting
Client-side scripting is the process of sending JavaScript code along with the web page. That code gets executed either during the loading of the web page or after the web page has been loaded.
There are a couple of great advantages of client-side scripting. One is that data processing is done on the client side, which makes it easier to scale applications with large numbers of users. Another is that browser events can often be handled locally without the need to send requests to the server. This enables you to make interfaces respond to user interaction much more quickly.
JavaScript, jQuery, and now AngularJS are by far the most common forms of client-side scripting. Throughout this book, you learn why that is the case.
Figure 1.3 diagrams the flow of data between the web server and the browser for a simple client-side script that uses JavaScript to populate an empty <ul> element with a list of planets. Notice that the file located on the server is the same one sent to the browser, but in the browser, the JavaScript adds <li> elements for each planet. You do not need to fully understand the JavaScript code yet, just that the HTML is dynamically changed on the client and not the server.
FIGURE 1.3 The JavaScript is executed in the browser, and so the HTML document rendered by the browser is different from the one that was originally sent.
Server-Side Scripting
There are two major types of server-side scripting. These are server-side templates and AJAX request handlers. Each of these methods requires that code be written on the server to either dynamically generate an HTML document before it is sent to the browser or to dynamically generate data that can be consumed by a client-side application.
Server-Side Templates
The first type is to use a PHP, .Net, Java, or other type of application that is run on the server that generates the HTML page, or at least parts of the HTML page, dynamically as they are requested by the client.
The main advantages of this type of server-side scripting is that data processing is done completely on the server side and the raw data is never transferred across the Internet; also, problems and data fix-ups can be done locally within the server processing.
The disadvantage of this type of server-side scripting is that it requires more processing on the server side, which can reduce the scalability of some applications.
Figure 1.4 illustrates using a simple Node.js application on the server that will dynamically create an HTML document that populates a list of planets. In the example in Figure 1.3, PHP code is used, and the web server’s PHP engine will replace the code in the <?php> tag with the output generated by the PHP script.
FIGURE 1.4 The PHP script is executed on the web server, and so the HTML document sent to the browser is different from what is actually contained on the server.
You don’t necessarily need to understand how the code works at this point; you only need to understand that the HTML document is dynamically generated on the server and not the client.
AJAX Handlers
The second major type of server-side scripts are applications that return raw data in the form of raw JSON or XML to the browser in response to an Asynchronous JavaScript plus XML or AJAX request. AJAX requests are designed to allow JavaScript running in the browser client to get raw data from the server.
AJAX reduces the need to reload the web page or load other web pages as the user interacts. This reduces the amount of data that needs to be sent with the initial web server response and also allows web pages to be more interactive.
For a simple example of AJAX, we’ve constructed two scripts—Listing 1.3 and Listing 1.4. Listing 1.3 is an HTML document with JavaScript that runs on the client after the page is loaded. The JavaScript makes an AJAX request back to the server to retrieve the list of planets via a server-side script. Listing 1.4 simulates the JSON data that could be returned by the server-side script. The list of planets returned is then used to populate the HTML list element with items.
LISTING 1.3 ajax.html A Simple JavaScript Client-Side Script Executes an AJAX Request to the Server to Retrieve a List of Planets to Use When Building the HTML List Element
01 <!DOCTYPE html> 02 <html> 03 <head> 04 <title>AJAX</title> 05 <meta charset="utf-8" /> 06 <script> 07 var xmlhttp = new XMLHttpRequest(); 08 function loadPlanets(){ 09 xmlhttp.open("GET","/lesson01/data.html",false); 10 xmlhttp.send(); 11 var planets = JSON.parse( xmlhttp.responseText ); 12 var ulElement = document.getElementById("planetList"); 13 for (var planet in planets){ 14 var listItem = ulElement.appendChild(document.createElement("li")); 15 listItem.appendChild(document.createTextNode(planets[planet])); 16 } 17 } 18 </script> 19 </head> 20 <body onload="loadPlanets()"> 21 <ul id="planetList"> 22 </ul> 23 </body> 24 </html>
LISTING 1.4 data.html Dynamic JSON Data Generated by a Server-Side Script
01 [ 02 "Mercury", 03 "Venus", 04 "Earth", 05 "Mars" 06 ]
Figure 1.5 illustrates the flow of communication that happens during the AJAX request/response. Notice that a second request is made to the server to retrieve the list of cities.
FIGURE 1.5 Using an AJAX request, JavaScript can send an additional request to the server to retrieve additional information that can be used to populate the web page.