9 Javascript Advanced Features

Web Technology I · Unit 9

JavaScript Advanced Features

Exam-focused notes for JavaScript Advanced Features (Web Technology I, BIT251): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.

JavaScript Advanced Features in short

This chapter covers features that make JavaScript useful in real web applications. They are cookies, error handling and popup boxes. AJAX is also included, which updates a page without reloading it.

JavaScript Advanced Features: notes

JavaScript cookies creation and usage

A cookie is a small piece of text stored by the browser for a website. It helps a site remember a user, because HTTP is stateless. Uses include login sessions, language choice and shopping carts.

A cookie has a name, a value and optional settings.

  • expires or max-age: when the cookie dies. Without it, the cookie ends with the browser session.
  • path: which paths can read the cookie.
  • domain: which domain can read it.
  • secure: send only over HTTPS.

Cookies are about 4 KB in size at most, and are sent to the server with every request. JavaScript uses document.cookie.

function setCookie(name, value, days) {
  var d = new Date();
  d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = name + "=" + encodeURIComponent(value) +
                    "; expires=" + d.toUTCString() + "; path=/";
}

function getCookie(name) {
  var parts = document.cookie.split("; ");
  for (var i = 0; i < parts.length; i++) {
    var kv = parts[i].split("=");
    if (kv[0] === name) return decodeURIComponent(kv[1]);
  }
  return "";
}

setCookie("user", "Ram", 7);
console.log(getCookie("user"));

To delete a cookie, set its expiry date in the past.

Exception handling try catch

An exception is a runtime error. If it is not handled, the script stops. The try...catch block lets the program deal with the error and continue.

  • try holds code that might fail.
  • catch (e) runs if an error happens. The object e has name and message.
  • finally always runs, whether or not an error happened.
  • throw creates an error on purpose.
try {
  let result = undefinedFunction();
} catch (e) {
  console.log("Error: " + e.message);
} finally {
  console.log("Done");
}

Common error types are SyntaxError, ReferenceError, TypeError and RangeError. Syntax errors are found before the code runs, so try cannot catch them in the same script.

What this unit covers

  • JavaScript cookies creation and usage
  • Exception handling try catch
  • Division by zero error handling
  • Popup boxes alert confirm prompt
  • XMLHttpRequest object
  • AJAX concept and implementation

Popup boxes alert confirm prompt

2081 · 10 marks

Describe the uses of Popup Boxes in JavaScript with suitable examples.Write a JavaScript program that will take two strings as input and display concatenation of them as output.[6+4]

--- (a) Popup Boxes in JavaScript JavaScript provides three types of built-in popup (dialog) boxes to interact with the user. These are browser-level dialog boxes used for displaying messages, taking input, or confirming actions. --- - Used to display a message or warning to the user. - The user ...

Open this answer on its own page →

AJAX concept and implementation

2081 · 5 marks

What is AJAX? Write a program to demonstrate the AJAX effect of your choice. [2+3]

Show solved answer

AJAX: Definition and Demonstration

What is AJAX? [2 marks]

AJAX stands for Asynchronous JavaScript and XML. It is a web development technique that allows a web page to communicate with a server and update parts of the page without reloading the entire page.

Key characteristics of AJAX:

  • Asynchronous: The browser does not wait for the server response; other operations continue normally.
  • Uses the built-in XMLHttpRequest object (or modern fetch API) to send and receive data from a server in the background.
  • Data can be exchanged in formats like XML, JSON, plain text, or HTML.
  • Provides a faster, smoother user experience by updating only the required portion of the webpage.

AJAX Program: Fetch and Display a Message on Button Click [3 marks]

File Structure

project/
  index.html
  data.txt        (server-side file to fetch)

data.txt

Hello! This message was loaded using AJAX without page reload.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 50px;
        }
        #result {
            margin-top: 20px;
            padding: 15px;
            background-color: #e0f7fa;
            border: 1px solid #00acc1;
            display: none;
            width: 400px;
        }
        button {
            padding: 10px 20px;
            background-color: #00acc1;
            color: white;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #007c91;
        }
    </style>
</head>
<body>

    <h2>AJAX Demonstration</h2>
    <p>Click the button to load content without refreshing the page.</p>

    <button onclick="loadContent()">Load Message</button>

    <div id="result"></div>

    <script>
        function loadContent() {
            // Step 1: Create XMLHttpRequest object
            var xhr = new XMLHttpRequest();

            // Step 2: Define what happens when response is received
            xhr.onreadystatechange = function() {
                // readyState 4 = request finished
                // status 200 = OK (success)
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var resultDiv = document.getElementById("result");
                    resultDiv.style.display = "block";
                    resultDiv.innerHTML = "<strong>Server Response:</strong> " 
                                         + xhr.responseText;
                }
            };

            // Step 3: Open a GET request to the server file
            xhr.open("GET", "data.txt", true); // true = asynchronous

            // Step 4: Send the request
            xhr.send();
        }
    </script>

</body>
</html>

How It Works (Step-by-Step)

StepDescription
1User clicks the "Load Message" button
2JavaScript creates an XMLHttpRequest object
3A GET request is sent asynchronously to data.txt on the server
4When the server responds (readyState == 4, status == 200), the response text is displayed inside the <div id="result">
5The page is NOT reloaded -- only the <div> content is updated

Output

When the button is clicked, the following appears on the page without any page refresh:

Server Response:
Hello! This message was loaded using AJAX without page reload.

Note: This program must be run on a web server (e.g., Apache, XAMPP, or VS Code Live Server) because AJAX requests cannot access local files directly due to browser security restrictions.

Open this answer on its own page →

XMLHttpRequest object

2080 · 5 marks

What is XMLHttpRequest Object? Write AJAX script to demonstrate use of XMLHttpRequest Object. [5]

The XMLHttpRequest (XHR) Object is a built-in browser API object that allows web pages to make asynchronous HTTP requests to a server without reloading the entire page. It is the core component of AJAX (Asynchronous JavaScript and XML) that enables communication between the client and server in t...

Open this answer on its own page →

Exception handling try catch

2080 · 5 marks

How exception handling is done in JavaScript? Write a JavaScript program that will handle an exception when an input number is divided by zero. [5]

Exception handling is a mechanism to handle runtime errors gracefully so that the normal flow of the program is not disrupted. JavaScript uses the try...catch...finally construct for exception handling. --- Keyword Purpose ------------------ try Wraps the code that might cause an error catch Catc...

Open this answer on its own page →

JavaScript cookies creation and usage

0 · 5 marks

What is cookie? Write a JavaScript code to create cookie object. [5]

A cookie is a small piece of data (text information) that is stored on the user's computer by the web browser. Cookies are used to remember information about the user between web page visits or browser sessions. - Stored as name=value pairs - Can have an expiry date - Associated with a specific d...

Open this answer on its own page →