Skip to main content

NETWORK BASICS

Network A system of interconnected computers and computerized peripherals such as printers is called computer network. This interconnection among computers facilitates information sharing among them. Computers may connect to each other by either wired or wireless media. A computer network consists of a collection of computers, printers and other equipment that is connected together so that they can communicate with each other.  


Network application
A Network application is any application running on one host and provides a communication to another application running on a different host, the application may use an existing application layer protocols such as: HTTP(e.g. the Browser and web server), SMTP(e.g. the email-client). And may be the application does not use any existing protocols and depends on the socket programming to communicate to another application. So the web application is a type of the network applications. 
There are lots of advantages from build up a network, but the th…

Creating Animations, Working with Graphics, and Accessing Data

Coding Animations by Using JavaScript
Coding Animations by Using JavaScript

Animation is the display of a sequence of static images at a fast enough speed to create the illusion of movement. Regarding the user interface, animation has to do with changing a display to make it dynamic—not just a one-time change but a seamless one. JavaScript is flexible enough to produce spectacular animation effects, in the right hands. Recursion is a key part of animation. Recursion is a programming technique in which a function calls itself. A common technique in JavaScript animation is to use set-timeout recursively, that is, to have it invoke another execution of the same function from which the set-timeout() was called. This is generally the most effective way to introduce a “timing element” into JavaScript.

Outside of programming, recursion isn’t always considered good behavior. If you’re writing a dictionary or glossary term, for example, it’s a best practice to define a term without using the same words that appear in the term. Let’s say you’re defining the word “politics.” A definition such as “the field of political behavior” might be frowned upon by many editors because of the use of “political.” For computing, recursion turns out to be not only permissible but powerful.

Creating Animations

Animation, like other JavaScript effects, is under computational control. That means that sufficiently clever coding can make animation do what you choose. The move_paragraph() function in the source code of the following exercise is considered recursive because move_paragraph itself appears in the last statement that defines the function. This exercise creates a continuously updated animation in the style of a “ticker.”

CREATE A SIMPLE ANIMATION GET READY. 

To create a simple application, perform the following steps: 1. Create L9-js1.html with the following content: <!doctype html> <html> <head> <title>Animate with JavaScript</title>
<script type = "text/javascript">  // Create a "ticker-tape" effect by sliding  // the paragraph of text one pixel to the   // right, over and over, until the right-hand  // limit of 300 pixels is reached.  At that  // point, restart the animation all the way  // to the left.
function move_paragraph() {    next = current + "px";    current += 1;    if (current > 300) { current = 0;    }     paragraph.style.left = next; // Pause for 18 milliseconds before // the next move.    var rate = 18;    set-timeout(move_paragraph, rate); } function init() {    paragraph = document.getElementById("original");    paragraph.style.position = "absolute";    current = 0;    move_paragraph(); } </script> </head> <body onload = "init();">
<h1>Animate with JavaScript</h1> <p id = "original">Do you see me scrolling across the   screen?</p>
</body> </html> 2. Open L9-js1.html in your Web browser. Does the paragraph move across your screen, as shown in Figure 9-1? 3. Close the file but leave the editing tool and Web browser open.

CREATE AN INTERACTIVE ANIMATION

To create an animation responsive to the action of a user, perform the following steps: 1. Create L9-js2.html with the following content:
<!doctype html> <html> <head> <title>Animate with JavaScript</title>
<script type = "text/javascript">  // This page acts much the same as L9-js1.html  // did, with the exception that the frequency  // of moving the paragraph depends on the numeric  // value the end-user has entered in the input  // field. function move_paragraph() {    next = current + "px";    current += 1;    if (current > 300) { current = 0;    }    paragraph.style.left = next;    var rate = document.getElementById("rate").value;    set-timeout(move_paragraph, rate); } function init() {    paragraph = document.getElementById("original");    paragraph.style.position = "absolute";    current = 0;    move_paragraph(); } </script> </head> <body onload = "init();">
<h1>Animate with JavaScript</h1>  <!-- The number <input> tag is new with HTML5.  It provides a convenient way to enforce that  the end-user inputs a valid numeral within a  specified range. --> <form> <input id = "rate" type = "number" value = "18" min =   "5" max = "100"></input> </form> <p id = "original">Do you see me scrolling across the screen?</p>
</body> </html> 2. Open L9-js2.html in a Web browser. The interface displays, as shown in Figure 3. Replace the rate value (which is 18, initially) with a number that’s higher or lower, and note the effect on the animation. Do you see the speed of the animation accelerate and decelerate as you adjust the input? 4. Close the file but leave the editing tool and Web browser open if you complete the next exercise during this session.

Working with Images, Shapes, and Other Graphics

JavaScript can display different types of graphics, from JPG and PNG files to shapes like boxes and circles. One method is to use the createElement() method. This method creates a reusable function to display an image: function show_image(src, width, height, alt) {    var img = document.createElement("img");    img.src = src;    img.width = width;    img.height = height;    img.alt = alt;
    // Adds it to the <body> tag    document.body.appendChild(img); } To display the image, include this code: <button onclick="show_image ('path/filename', 276,110, 'Logo');"> Display logo</button> Displaying an image when a button is clicked is a fairly simple task. Actually creating graphics on the fly requires the canvas element or SVG. This lesson covers graphics creating using canvas.

Manipulating the Canvas with JavaScript

HTML5’s canvas element is a drawing area under programmatic control. The only graphical elements common in earlier HTML were static, such as PNG and JPG. Dynamic and especially interactive effects were difficult. Canvas changes all that. As you learned in Lesson 2, the canvas element creates a container for graphics, and uses JavaScript to draw the graphics dynamically. With JavaScript, you can also animate objects by making them move, change scale, and so on. To draw a canvas object, the primary constructs you use are the getElementById() function to find the canvas element, and canvas.getContext (sometimes abbreviated to c.getContext) to create the canvas object. You can then use a variety of methods to draw shapes, include images, and so on. Entire applications, including impressive games and simulators, have been built with the HTML5 canvas.

USE CANVAS TO CREATE A CLOCKFACE WITH MOVING HANDS GET READY. 

To demonstrate use of HTML5’s canvas, perform the following steps: 1. Create L9-js3.html with following content:
<!doctype html> <html> <head> <title>Analogue clockface illustrates JavaScript's   control of canvas</title>
<script type = "text/javascript"> function draw_leg(fraction) {    dctx.lineTo(center_x + length * Math.sin(2 *   Math.PI * fraction), center_y - length * Math.cos(2 *   Math.PI * fraction)); }
function init() {    var canvas =  document.getElementById("clockface"); // The following variables are created as // globals, so they can conveniently be // accessed by other functions.    dctx = canvas.getContext('2d');    dctx.fillStyle = "black";    center_x = 100;    center_y = 100;    length = 100;    show_hands(); }
// A single hand is drawn as an isosceles triangle   // from the center to the edge of the clockface.
function show_hand(fraction, width) {    dctx.beginPath();    dctx.moveTo(center_x, center_y);    draw_leg(fraction - width);    draw_leg(fraction + width);    dctx.fill(); }
function show_hands() { // Erase anything already present in the area // that represents the clock face.    dctx.clearRect(0, 0, 200, 200); // What is the time *now*?    var now = new Date();     seconds = now.getSeconds();    minutes = now.getMinutes() + seconds / 60;    hours = now.getHours() + minutes / 60; // The second hand is "skinniest" of the three.    show_hand(seconds / 60, 0.002);    show_hand(minutes / 60, 0.005); // The hour hand is twice as wide as the minute // hand.    show_hand(hours / 12, 0.01);    var rate = 1000;    set-timeout(show_hands, rate); } </script> </head> <body onload = "init();">
<h1>Analogue clockface illustrates JavaScript's   control of canvas</h1> <canvas id = "clockface" width = "200" height =   "200"></canvas>
</body> </html> 2. Open L9-js3.html in a Web browser. The display appears, as shown in Figure 9-3. Close the file and the Web browser, but leave the editing tool open if you complete the next exercise during this session.

In another example, the following exercise creates an abstract drawing made by placing blocks on an HTML5 canvas. The exercise illustrates that it takes relatively few lines of JavaScript to produce quite complicated effects.

CREATE ANIMATED BOXES USING CANVAS GET READY. 

To create animated shapes using the canvas element, perform the following steps: 1. Create L9-js4.html with the following content: <!doctype html> <html> <head> <title>Blocks</title>
<script type = "text/javascript"> // This page is "for play"—it just places blocks of // color on the screen with a bit of randomization, // to achieve mildly interesting visual effects. // Recursion is used in a couple of distinct ways // below:  place_blocks() calls draw_spiral(), and // draw_spiral() calls either place_blocks() or // draw_spiral(), depending on how much of a spiral // has been most recently drawn. function init() {    var canvas =    document.getElementById("drawing_area");    dctx = canvas.getContext('2d');    place_blocks(); } function draw_spiral() { // Once a block moves outside the drawing // area, stop the current spiral, and create // a new one.    if (x > 500 || y > 500 || x < 0 || y < 0) { place_blocks();    }    ratio = 1.6;    newx = x;    newy = y;    dx = size;    dy = size; // Each block is turned 90 degrees away // from the last one.    switch (direction) { case "up": dy = -size; newy += dy; direction = "left"; break;
case "left": dx = -size; dy = -size; newx += dx; direction = "down"; break; case "down": dx = -size; newy += dy; direction = "right"; break; case "right": newx += dx; direction = "up"; break;
    }    dctx.fillRect(x, y, dx, dy); // Each successively-drawn block is larger // than the last.    size *= ratio;    x = newx;    y = newy;    set-timeout(draw_spiral, delay); } function place_blocks() {     dctx.fillStyle =   '#'+Math.floor(Math.random()*16777215).to-string(16   );    x = 100 + 300 * Math.random();    y = 100 + 300 * Math.random();    delay = 100 + 2000 * Math.random();    size = 3 + 7 * Math.random();    direction = "up";    draw_spiral(); } </script> </head> <body onload = "init();">
<h1>Blocks</h1> <canvas id = "drawing_area" width = "500" height =   "500"></canvas
</body> </html> 2. Open L9-js4.html in a Web browser. The screen fills with colored blocks, as shown in Figure 9-4. 3. Close the file but leave the editing tool and Web browser open if you complete the next exercise during this session.

Sending and Receiving Data

Part of the power of modern computer applications is their ability to coordinate information from many sources into a useful display: JavaScript can bring together server-side databases of customer history, memory local to the desktop or handheld in use with current shopping selections, the contents of the current page, and remote updates of pricing or weather details for comparison and calculation. Creating JavaScript programs that send and receive data is challenging, not because the concepts are hard but because the JavaScript application has a different structure than any of the others. Nearly all the JavaScript examples in Lessons 8 were constructed as small, self-contained HTML pages. Each individual page can be loaded in a browser and fully exercised in the browser in isolation. However, a JavaScript program that sends and receives data must have more parts: there must be a receiver or sender somewhere with which your JavaScript program can exchange data. Most often, HTML pages or mobile applications communicate with a networked server at some central application. 
JavaScript data transactions often are presented as conceptually difficult and available only to those who have mastered AJAX, XML, JSON, and a complicated stew of other acronyms. This is not true. You already understand functions: functions are special little boxes that you supply zero or more arguments, then the box does something and perhaps returns a result to you. JavaScript network communication is much the same: pass zero or more pieces of data, and receive a result back. The great difficulty lies in first setting up your own “laboratory” with the parts necessary to make this dialogue work. Once you have that first channel working smoothly, you’ll find that you quickly learn the security, control-flow, and encoding rules peculiar to JavaScript data communications. One of the most essential techniques for data transfer involves the XMLHttpRequest API (sometimes abbreviated as XHR). XMLHttpRequest enables you to use JavaScript to pass data in the form of text strings between a client and a server. The general syntax might look like the following: function load(url, data, callback) {    var xhr = new XMLHttpRequest();    xhr.open("GET", url, true);    xhr.onload = function() { callback(xhr.responseText);    }    xhr.send(data); }
The XMLHttpRequest object creates a call to the server. The open method specifies the HTTP method for contacting the server and provides the server’s Web address. The callback function gets a response from the server. Finally, xhr.send(data) sends the data. A few subsequent exercises, as you’ll soon see, require a Web server; the Application Cache, for instance, only exists for sites accessed through a network connection. With the right approach, however, nearly any Web server makes a good practice companion. Your instructor will set up access to a Web server so you can try out Application Cache with little difficulty. To send and receive data explicitly in JavaScript is different; to make it work requires a dynamic Web server and server-side programming. Be sure you keep these distinctions clear: • Most JavaScript functionality: can be demonstrated with a browser from the local desktop filesystem. • ApplicationCache and a few other HTML5 facilities in JavaScript: require a Web server. Any Web server will do. • XmlHttpRequest and comparable JavaScript data transmission facilities, including some introduced by HTML5: require a dynamic Web server. In the absence of a dynamic Web server, the following exercise shows a very simple example of data access. When you do choose to work with Web servers, you’ll have quite a selection of alternatives that are relatively easy for a newcomer to Web service. wamp for windows, mamp for mac, and lamp for linux are among the simplest starting points.

ACCESS DATA GET READY. 

As a minimal example of JavaScript’s ability to access data, perform the following steps: 1. Create L9-js5.html with the following content: <!doctype html> <html> <head> <title>JavaScript accesses data</title><script type = "text/javascript">
function init() {    var paragraph_object =    document.getElementById('paragraph');     message = "Notice that the title of this page is   '" + document.title + "'.";    paragraph_object.innerHTML = message; }
</script> </head> <body onload = "init();">
<h1>JavaScript accesses data</h1> <p id = "paragraph"></p>
</body> </html> 2. Open L9-js5.html in a Web browser. The display appears, as shown in Figure 9-3. Notice that JavaScript can access HTML content. 4. Close the file but leave the editing tool and Web browser open if you complete the next exercise during this session.
What’s the point of this example? If a programmer needs the title of a Web page, why wouldn’t she just copy and paste it from the HTML? One frequent answer: JavaScript of this sort is intended for a site-wide library. There might be a style or policy that is supposed to apply to all pages. In such a case, it’s far more convenient and trouble-free to encapsulate the policy in a JavaScript library that knows how to retrieve the title for itself, rather than having to copy-and-paste the title of all pages for the entire site. Each page then includes an identical copy of the JavaScript library.

“Policy” is a word programmers use to mean, roughly, “style of action.” A visual style might be something we humans express as “every page should appear with this particular subtle background image”; an example of a policy is “every page should make its text visible nearly instantaneously, and should still be readable even if resized horizontally.” JavaScript helper functions and site-wide standards for coding can help realize policies of this sort. 

“Encapsulate” is a bit of jargon programmers often say. In the JavaScript application that drew an analogue clockface on a canvas, the show_hand() function “encapsulates” all the trigonometry involved in drawing a single hand, whether for the hours, minutes, or seconds. The programmer uses show_hand() without concern for the details of what’s “inside” (the capsule). For most people, it’s far easier to “draw a box” or capsule around a piece of functionality, give the capsule a name, and think about the capsule as a whole, rather than looking at all its parts each time it’s used. 

Transmitting Complex Objects and Parsing

In real-world programming, JavaScript can handle highly complicated operations. One might, for instance, receive an involved report on gasoline prices at a long list of retail outlets and need the ability to isolate just one of those figures. Parsing is a term used to describe analysis of complex information into constituent parts.

PARSE COMPLEX DATA 

GET READY. To demonstrate JavaScript’s ability to parse complex data, perform the following steps: 1. Create L9-js6.html with the following contents: <!doctype html> <html> <head> <title>Parsing complex data</title>
<script type = "text/javascript">
  // The next statement needs to appear  // on a single line. sample_data = "Mobil-17: 3.49; Kroger-03: 3.36;    Exxon-01: 3.59; Kroger-04: 3.49; Valero-A: 3.41; Chevron-01: 3.52"; of_interest = "Kroger-04";
// sample_data is an example of a typical piece of // structured data:  a string with parts separated // by semi-colons, where each of the parts has two // sub-parts separated by a colon.  Many other formats // are possible.  To parse this particular format, // init() splits on two distinct separators. function init() {    var paragraph_object =   document.getElementById("paragraph");    var data_list = sample_data.split(';');    for (j = 0; j < data_list.length; j++) { parts = data_list[j].split(':'); var site = parts[0].trim() if (site == of_interest) {
var message = "Given the sample data '" +   sample_data + "', this program parsed out the   price $" + parts[1].trim() + " for the " + site +    " site."; paragraph_object.innerHTML = message; }    } }
</script> </head> <body onload = "init();">
<h1>Parsing complex data</h1> <p id = "paragraph">Welcome.</p>
</body> </html> 2. Open L9-js6.html in a Web browser. The display should look like Figure 9-6.
3. Close the file but leave the editing tool and Web browser open if you complete the next exercise during this session.
JavaScript and freely available JavaScript libraries supply a wealth of parsing facilities. Extraction of data from a human-readable external Web page is only one instance among many of how JavaScript can parse data. For example, you can also use a subset of JavaScript called JSON (JavaScript Object Notation) to exchange JavaScript objects with a server. Using the JSON.parse and JSON.stringify APIs, the code might look like the following: function loadJSON(url, data, callback) {    var xhr = new XMLHttpRequest();    xhr.open("GET", url, true);    xhr.onload = function() { callback( JSON.parse(xhr.responseText) );    }    xhr.send( JSON.stringify(data) ); }
loadJSON("my.json", { id : 1 }, function(response) {    setTitle(response.title); });
This code is almost identical to the XMLHttpRequest code sample earlier in the lesson. The XMLHttpRequest object creates a call to the server, and the open method specifies the HTTP method for contacting the server and provides the server’s Web address. The callback function uses JSON parse to get a response from the server. When the server responds, the JSON.parse API is called, which creates the JavaScript object. The object is sent back to the server. The data, however, is “stringified” first.

Loading and Saving Files

Many Web or mobile applications include a function to upload a file. This has long been a weakness of HTML, in that there is no effective way to specify, for example, “only allow uploads of images, as opposed to documents, and only if the images occupy less than 1.1 megabytes.” Without this capability, it too often happens that users accidentally attempt to upload something other than what they intended or the application supports, and network delays make correction of the error a time-consuming process. HTML5’s ability to access local files means that an image intended for upload can be advertised as a thumbnail and validated before the upload. JavaScript’s immediate actions help make uploading a more interactive and error-free process.

ACCESS A LOCAL FILE GET READY. 

To demonstrate JavaScript’s ability to access a local file, perform the following steps: 1. Create L9-js7.html with the following content: <!doctype html> <html> <head> <title>JavaScript accesses local files</title>
<script type = "text/javascript"> function acknowledge(file_handle) {    var size = file_handle.size;    var fname = file_handle.name;    var message = "You have chosen the file '" +   fname + "'.  This appears to be a recognizable   image, totaling " + size + " bytes in size.";    alert(message);
}
function complain(fname) {     var message = "The file named '" + fname + "'   does not appear to have an acceptable extension.";    alert(message);
function handle_file_selection(item) {    var f = item.files[0];    var fname = f.name;    var last_index = fname.lastIndexOf('.');    if (last_index == -1) { complain(fname); return;    }    var ext = fname.substr(last_index + 1);    if (ext.toLowerCase() in {'gif': '', 'jpg': '', 'png': '', 'tif': '' }) { acknowledge(f);    } else { complain(fname);    } }
</script> </head> <body>
<h1>JavaScript accesses local files</h1> <input type = 'file' on-change = 'handle_file_selection(this);' />
</body> </html> 2. Open L9-js7.html in a Web browser. 3. Click Browse and then navigate to and select a file on your local computer that’s not an image. Click Open. The display should look like Figure 9-7. The message box informs you that you selected the wrong file type. Click OK to close the message box.
4. Repeat step 3 and this time open a file that is an image. The resulting message box should look similar to Figure 9-8, informing you that you selected an acceptable type of file. Click OK to close the message box.
5. Close the file but leave the editing tool and Web browser open if you complete the next exercise during this session.
Notice this program doesn’t actually upload the selected file. The point of this exercise is to show how JavaScript can access and manage the file and its contents even before uploading.

Using the Application Cache (App-cache)

App-cache saves a copy of your Web site files locally, in a structured form. The files include HTML, CSS, and JavaScript, along with other resources the site needs to run. After a visitor has visited the site once, subsequent visits will load resources quickly from the local copy rather than waiting on a network connection. Recall from Lesson 1 that App-cache uses a text file called a cache manifest to specify the files a Web browser should cache offline. Even if a user refreshes the browser while offline, the page will load and work correctly. App-cache is not the same as a browser’s cache. Whereas a browser’s cache saves all Web pages visited, App-cache saves only the files listed in the cache manifest. You can apply App-cache to a single Web page or an entire site.For App-cache to work, the Web server must be configured with the correct MIME type, which is text/cache-manifest. In addition, the preferred file extension for manifest files is .app-cache. 

USE APP-CACHE GET READY. 

To demonstrate AppCache, perform the following steps: 1. Obtain privileges to use a Web server from your instructor. The server must have the MIME type configured to text/cache-manifest. AppCache is only effective for network accesses; it does not act when a Web resource is local. 2. Create L9-appcache.html with the following content: <!doctype html> <html manifest = "test.appcache"> <head> <title>Minimal AppCache example</title>
</head> <body> <h1>Minimal AppCache example</h1> <p> This page should reload after disconnecting from the Internet and refreshing the Web page. </body> </html> 3. Close L9-appcache.html and then upload the file to the Web server. The instructor will give you the Web address of the file. 4. In a Web browser, navigate to the Web address. The L9-appcache.html file opens. 5. Observe the display as shown in Figure 9-9. Does the page reload as expected?
6. Disconnect your local computer from the Internet. 7. Confirm that you cannot access Web pages—the MSDN homepage, for example. 8. Refresh the image of L9-appcache.html in your browser. 9. Note that it displays quickly, even though L9-appcache.html is now unavailable. 10. Close the HTML file but leave the editing tool and Web browser open if you complete the next exercise during this session.

Understanding and Using Data Types

Values in JavaScript appear in special appearances or “dressings”, called data types. Most often encountered are strings and numbers. “ABCD” and “1234” are both examples of strings; the latter just happens to include only digits. The numeral “3” is a number, but “3 dollars” is a string. Other data types are more specialized, such as array, Boolean, null, object, and undefined. Their use is relatively rare, and outside the scope of this lesson. The main significance of data types at this level is that their definition leads to a few surprises. In JavaScript, the following example has the value 123:
"'1' + 2 + 3" But the following has the value 6 or ‘33’, depending on the JavaScript interpreter used:
"1 + 2 + '3'" There are rules that define all this behavior, and each of the data types has its uses. For the purpose of this lesson, be aware of the distinction between, for example, a number and the characters that represent that number. If you accidentally run into a computation where JavaScript’s handling of types surprises you, study MSDN reference material on data types. In the meantime, program JavaScript simply and carefully.

Using JavaScript to Validate User Form Input

You learned about HTML form input and validation in Lesson 3. With JavaScript, your forms can do much more for you and your end users. Suppose, for example, that an end user needs to enter a serial number of the form XXX-XXXXX-X, where each X is a digit. In the early days of Web application, end users typed this in as best they could, then “submitted” a complete form. The server checked for any errors, and reported them back as best it could. With JavaScript, client-side entry validation in the form of feedback and correction is instantaneous. 

MANAGE A FORM WITH JAVASCRIPT GET READY. 

To demonstrate JavaScript’s ability to manage a form, perform the following steps: 1. Create L9-js8.html with contents: <!doctype html> <html> <head> <title>Form management</title><script type = "text/javascript">
// The action of the correct()
   function is to
// test the characters the user has
   entered
// against the pattern 'XXX-XXX-XX
   X'.  If the
// user's entry does not match this
   pattern,
// remove the last character. This
   gives the
// user the impression that she or
   he can only
// enter valid characters. function correct() {    var input_object =   document.getElementById("serial");    var value = input_object.value;    var current_length = value.length;    if (current_length) { var last_character =   value.substring(current_length - 1); switch (current_length) { case 4: case 8: case 11: if (last_character != '-') { value = value.substring(0,   current_length - 1); } break; default: if (!/\d/.test(last_character)) { value = value.substring(0,   current_length - 1); } } if (current_length > 12) { value = value.substring(0, current_length   - 1); } current_length = value.length; switch (current_length) { case 3: case 7: case 10: value += "-"; } input_object.value = value;    } }
</script> </head> <body><h1>Form management</h1> <form> Enter here a serial number in the pattern XXX-XXX-XX   X, where each X is a digit: <input id = "serial"   type = 'text' size = '12' onkeyup =   "correct();">. </form>
</body> </html> 2. Open L9-js8.html in a Web browser. The display appears, as shown in Figure 9-3. Begin typing characters. Notice that the entry field accepts only characters that match the XXX-XXX-XX-X pattern, ignoring any that don’t match. 4. Close the file but leave the editing tool and Web browser open if you complete the next exercise during this session.
A real-world application would require more validation: it’s not enough that an entry look like a serial number, but the application also should confirm that it is a serial number. While an end user might still enter a value incorrectly, simple JavaScript validation of form inputs goes a long way toward helping ensure success. Also, even with this validation, a sufficiently determined end user can use the mouse to enter certain values that don’t match the serial-number pattern. A more sophisticated validator might trap mouse movements and deletions.

Understanding and Using Cookies

Cookies are small text files that Web sites save to a computer’s hard disk that contain information about the user and his or her browsing preferences. The content of cookies change as a user revisits a site and selects different items or changes preferences. From the perspective of JavaScript, a cookie is a variable, and you use JavaScript to both create and retrieve cookies. Suppose you’re in charge of a computer game coded in HTML and JavaScript. It works well enough, but requires a user to choose a “level” each time he begins a new game. Wouldn’t it be better to have the game assume that the user wants to start one level beyond his last game, with an option to adjust? Not only is that better, but JavaScript’s cookie capabilities make it easy to program.

USE COOKIES GET READY. 

To demonstrate JavaScript’s ability to retain information on the desktop computer even with the browser shut down, perform the following steps: 1. Create L9-js9.html with the following content: <!doctype html> <html> <head> <title>Use of cookies</title>
<script type = "text/javascript">
function getCookie(c_name) {    var i,x,y,ARRcookies=document.cookie.split(";");    for (i=0;i<ARRcookies.length;i++)    {   x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));   y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } }
function init() {    var message;    level_object  = document.getElementById("level");    var welcome = document.getElementById("welcome");    var level = getCookie("level");    if (level == null || level == '') { message = "It appears this is your first time   to play. You will start at level 1."; level = 1;    } else { message = "When you last played, you reached   level " + level +".  You will start there now.";    }    welcome.innerHTML = message;    level_object.value = level; }
function save_level() {    setCookie("level", level_object.value, 10); }
function setCookie(c_name,value,exdays) {    var exdate=new Date();    exdate.setDate(exdate.getDate() + exdays);    var c_value=escape(value) + ((exdays==null) ? ""   : "; expires="+exdate.toUTC String());    document.cookie=c_name + "=" + c_value; }
</script> </head> <body onload = "init();">
<h1>Use of cookies</h1> <p id = "welcome">Welcome.</p> <form> You can update your level at any time.  It is   currently set at <input id = "level" type = "number" min = "1" max =   "100" oninput = "save_level();" />. </form>
</body> </html> 2. Obtain privileges to use a Web server from your instructor. Cookies can only be enabled for Web pages accessed through the network, not locally. 3. Upload L9-js9.html to the Web server using a file transfer program, as described by your instructor. Your instructor also needs to give you the Web address for the file. 4. In a Web browser, use the Web address to navigate to and open L9-js9.html. 5. Notice the level at which you start, as shown in Figure 9-11.6. Pretend you’ve played for a while and reached a different level. Enter that level in the input area. 7. Close the application’s window. 8. Open L9-js9.html again. Do you see how the application “remembered” your position from one browser session to another? 9. Using your browser’s preferences settings, remove the cookie created in this exercise or, if more convenient, remove all cookies. 10. Open L9-js9.html again. Note that your level has reverted to the default of 1. 11. Close the file but leave the editing tool and Web browser open if you complete the next exercise during this session.

Understanding and Using Local Storage

Cookies have limits. They have a bad reputation in some circles for contributing to spread of personal information without permission, and they are clumsy for storage of all but the simplest data. HTML5’s LocalStorage has better security and makes programming easier than it is with cookies.

SAVE TO LOCAL STORAGE GET READY. 

To demonstrate JavaScript’s ability to save information without cookies, perform the following steps: 1. Create L9-js10.html with the following content: <!doctype html> <html> <head> <title>Use of local storage</title>
<script type = "text/javascript"> // This page demonstrates a simple model for // saving a player's "level" in local storage. function init() {    var message;    level_object  = document.getElementById("level");    var welcome = document.getElementById("welcome"); // "localStorage" is a keyword for an HTML5// capable browser.  "localStorage.level" is // a variable name chosen for use by this // particular page.    var level = localStorage.level;    if (level == null || level == '') { message = "It appears this is your first time   to play. You will start at level 1."; level = 1;    } else { message = "When you last played, you reached   level " + level +".  You will start there now.";    }    welcome.innerHTML = message;    level_object.value = level; }
function save_level() {    localStorage.level = level_object.value; }
</script> </head> <body onload = "init();">
<h1>Use of local storage</h1> <p id = "welcome">Welcome.</p> <form> You can update your level at any time.  It is   currently set at <input id = "level" type = "number" min = "1" max =    "100" oninput = "save_level();" />. </form>
</body> </html>
2. Obtain privileges to use a Web server from your instructor. Local storage can only be enabled for Web pages accessed through the network, not locally. 3. Upload L9-js10.html to the Web server using a file transfer program, as described by your instructor. Your instructor also needs to give you the Web address for the file. 4. In a Web browser, use the Web address to navigate to and open L9-js10.html. 5. Notice the level at which you start, as shown in Figure 9-12.
6. Pretend you’ve played for a while and reached a different level. Enter that level in the input area. 7. Close the application’s window. 8. Open L9-js10.html again. Do you see how the application “remembered” your position from one browser session to another? 9. Close the file and any open programs or windows.

Comments

Popular posts from this blog

What if Analysis

What-If Analysis What-If Analysis in Excel allows you to try out different values (scenarios) for formulas. The following example helps you master what-if analysis quickly and easily.  Use scenarios to consider many different variables  A scenario is a set of values that Excel saves and can substitute automatically in cells on a worksheet. You can create and save different groups of values on a worksheet and then switch to any of these new scenarios to view different results. 
Create Different Scenarios 
Note: You can simply type in a different revenue and Cost into cell B2 and B3 respectively to see the corresponding result of a scenario in cell B4. However, what-if analysis enables you to easily compare the results of different scenarios.  
I. On the Data tab, click What-If Analysis and select Scenario Manager from the list. The Scenario Manager Dialog box appears  II. Add a scenario by clicking on Add.  III. Type a name (e.g. “First Case”), select cell B2 and B3 (represents “Revenue” and “…

PROFESSIONAL ENGLISH

Asking For and Giving Opinions on Likes and Dislikes

Words Meaning Sample Sentence Opinion A statement or judgment formed about some matter. Bhoomika gave her final opinion on the company’s matter. Dialogue A conversation between two or more people. Her dialogue stated her opinion about the company’s matter. Expression The action of making known one’s thought or feelings. Her expression was sad at the meeting. Frank An open, honest, and direct speech or writing Bhoomika is very frank with her friends. Recover Return to normal state of health, mind or strength. The company’s economic crisis will be recovered soon. Turmoil A state of great disturbance. The company is facing financial turmoil. Economics The branch of knowledge concerned with the production, consumption, and transfer of wealth. Bhoomika studied Economics at the State University. Betrayed Expose to danger by treacherously giving information to an enemy.

DAILY LIFE VOCABULARY

Apology Etiquette and Office Vocabulary 

Chapter Vocabulary

Word Meaning Sample Sentence Stressed A state of any mental or emotional tension. Ram seems much stressed after his poor exam. Launch An act of instance of starting something. The government launched a new scheme for the poor people. Error A mistake Ravi found a grammatical error in his new grammar book. Scold Blaming someone for any wrong doing Bhuvan scolded his employees for their poor performance. Accuse Claiming that someone has done something wrong. Bharati accuses her friend Chaya for stealing her necklace. Fair Good and honest Ravi got promoted for doing a fair job. Ashamed Embarrassed or guilty because of one’s action. <