Home > Articles > Web Development > Ajax and JavaScript

Introduction to Dynamic Web Programming with AngularJS, JavaScript, and jQuery

📄 Contents

  1. Understanding the Web Server/Browser Paradigm
  2. Setting Up a Web Development Environment
  3. Summary
  4. Q&A
  5. Workshop
This lesson from AngularJS, JavaScript, and jQuery All in One, Sams Teach Yourself gives 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.
This chapter is from the book

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

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

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

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

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

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020