CACS254 Scripting Language

Scripting LanguageUnit 116 min read

Scripting Languages: Types, Uses, and Client-Server Roles

Unit 1 of Scripting Language introduces scripting languages, their role in web development, and how they differ from compiled languages. It covers client-side vs. server-side scripting, common scripting languages (JavaScript, PHP), and their applications in dynamic web pages, form validation, and database interactions.

TAKEAWAYS:

  • Scripting languages execute dynamically on interpreters and are used for automation, web development, and rapid prototyping.
  • Client-side scripting (e.g., JavaScript) runs in the browser and enables real-time interactivity, while server-side scripting (e.g., PHP) processes data on the server.
  • Scripting languages like PHP and JavaScript are essential for handling user input, validating data, and interacting with databases.
  • Scripting languages are interpreted, platform-independent, and often embedded in other applications (e.g., HTML for JavaScript).
  • They enable rapid development and are widely used in web applications, CMS (e.g., WordPress), and APIs.
  • Security and error handling are critical in scripting languages due to their dynamic nature.

What Are Scripting Languages?

Scripting languages are high-level programming languages designed to automate tasks, control software applications, and glue together software components. Unlike compiled languages (e.g., C, C++), scripting languages are interpreted at runtime, making them ideal for rapid development and dynamic environments like web browsers or servers.

Key Characteristics of Scripting Languages:

mindmap
  root((Scripting Languages))
    Characteristics
      Interpreted: Executed line-by-line by an interpreter (e.g., PHP interpreter, JavaScript engine in browsers)
      Platform-Independent: Run on any platform with the interpreter (e.g., JavaScript in Chrome, Firefox, or Node.js)
      Embedded: Often integrated into other systems (e.g., JavaScript in HTML, PHP in Apache)
      Dynamic: Variables and functions can be modified at runtime
    Use Cases
      Web Development: Client-side (JavaScript) and server-side (PHP, Python)
      Automation: Shell scripting (Bash, PowerShell)
      Gluing Software: Connecting databases, APIs, or legacy systems
    Examples
      JavaScript: Client-side scripting for interactivity
      PHP: Server-side scripting for dynamic web pages
      Python: Scripting for automation and data analysis

Comparison: Scripting vs. Compiled Languages

Feature Scripting Languages (e.g., JavaScript, PHP) Compiled Languages (e.g., C, C++)
Execution Interpreted at runtime Compiled to machine code before execution
Speed Slower (interpreted) Faster (optimized machine code)
Portability High (runs on any interpreter) Low (needs recompilation for different platforms)
Development Speed Rapid (no compilation step) Slower (compilation required)
Use Case Web apps, automation, gluing software System software, high-performance applications
Error Handling Dynamic (runtime errors) Static (compile-time errors)

Client-Side vs. Server-Side Scripting

Scripting languages are categorized based on where they execute: client-side (browser) or server-side (web server).

1. Client-Side Scripting

Definition: Scripts executed in the user's browser (e.g., JavaScript). They enable interactivity without reloading the page. Examples:

  • Validating user input in forms before submission.
  • Dynamic content updates (e.g., loading comments without refreshing).
  • Animations and visual effects (e.g., sliders, dropdown menus).

How Client-Side Scripting Works:

sequenceDiagram
    User->>Browser: Enters data in form
    Browser->>JavaScript: Executes validation script
    JavaScript-->>Browser: Shows error if invalid
    Browser->>User: Displays error message
    User->>Browser: Submits corrected data
    Browser->>Server: Sends data to server (only if valid)

Example: JavaScript Form Validation

<form id="registrationForm">
  <label>Name:</label>
  <input type="text" id="name" required>
  <label>Email:</label>
  <input type="email" id="email" required>
  <button type="submit">Submit</button>
</form>

<script>
  document.getElementById("registrationForm").addEventListener("submit", function(event) {
    const name = document.getElementById("name").value;
    const email = document.getElementById("email").value;
    if (name === "" || email === "") {
      event.preventDefault(); // Stop form submission
      alert("Name and email are required!");
    }
  });
</script>

Trace Table for Validation:

Step Action Output
1 User submits empty form JavaScript checks inputs
2 name or email is empty event.preventDefault() called
3 Alert shows: "Name and email are required!" Form does not submit

2. Server-Side Scripting

Definition: Scripts executed on the web server (e.g., PHP, Python). They process data, interact with databases, and generate dynamic content. Examples:

  • Handling form submissions (e.g., storing user data in a database).
  • Generating personalized web pages (e.g., user dashboards).
  • Secure operations (e.g., password hashing, file uploads).

How Server-Side Scripting Works:

sequenceDiagram
    User->>Browser: Submits form
    Browser->>Server: Sends data via HTTP POST
    Server->>PHP: Executes script to process data
    PHP->>Database: Stores/queries data
    Database-->>PHP: Returns result
    PHP-->>Server: Generates HTML response
    Server->>Browser: Sends dynamic page
    Browser->>User: Displays updated content

Example: PHP Form Handling

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];

    // Validate inputs
    if (empty($name) || empty($email)) {
        die("Name and email are required!");
    }

    // Store in database (example using MySQLi)
    $conn = new mysqli("localhost", "user", "password", "database");
    $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $email);
    $stmt->execute();
    echo "Data saved successfully!";
}
?>

Trace Table for PHP Execution:

Step Action Output
1 User submits form Server receives POST data
2 PHP checks $_POST for name and email Validates inputs
3 If valid, connects to MySQL database Executes INSERT query
4 Database confirms insertion PHP echoes "Data saved!"

In the Real World

Scripting languages power the apps and services we use daily. Here’s how they work behind the scenes:

  1. eSewa (Nepal):

    • JavaScript: Validates user input in real-time (e.g., checking if a phone number is valid before submission).
    • PHP: Processes payments and updates user accounts on the server after form submission.
  2. Khalti (Nepal):

    • Client-Side (JavaScript): Dynamically updates transaction status without page reloads (e.g., showing "Processing..." then "Success").
    • Server-Side (PHP/Python): Handles secure payment processing and logs transactions in a database.
  3. Daraz (Global):

    • JavaScript: Manages the shopping cart (e.g., updating item quantities or calculating totals instantly).
    • PHP/Node.js: Processes orders, checks inventory, and generates shipping labels on the server.
  4. Pathao (Nepal):

    • JavaScript: Displays real-time driver locations on the map using APIs (e.g., Google Maps).
    • Server-Side (Python/Java): Matches riders with drivers, calculates fares, and updates ride statuses.
  5. NEPSE (Nepal Stock Exchange):

    • JavaScript: Updates stock prices in real-time on the dashboard (e.g., fetching data via AJAX).
    • PHP: Authenticates traders and logs trades in the database.

Common Scripting Languages

Here are the most widely used scripting languages in web development:

1. JavaScript

  • Role: Client-side scripting (browser) and server-side (Node.js).
  • Key Features:
    • Runs in all modern browsers.
    • Enables DOM manipulation, AJAX, and event handling.
    • Used for frameworks like React, Angular, and Vue.js.
  • Example Use Case:
    • Pathao’s Ride Tracking: JavaScript fetches driver locations from a server every 5 seconds and updates the map dynamically.

2. PHP

  • Role: Server-side scripting (e.g., WordPress, Laravel).
  • Key Features:
    • Embedded in HTML (<?php ... ?>).
    • Integrates with databases (MySQL, PostgreSQL).
    • Powers ~77% of all websites.
  • Example Use Case:
    • eSewa’s Payment System: PHP processes payment requests, checks user balances, and updates transaction records.

3. Python

  • Role: Scripting for automation, data analysis, and server-side apps (e.g., Django, Flask).
  • Key Features:
    • Easy syntax, vast libraries (e.g., NumPy, Pandas).
    • Used in backend services (e.g., Instagram, Dropbox).
  • Example Use Case:
    • Khalti’s Fraud Detection: Python scripts analyze transaction patterns to flag suspicious activity.

4. Bash

  • Role: Shell scripting for Linux/Unix automation.
  • Key Features:
    • Automates repetitive tasks (e.g., backups, file management).
    • Used in DevOps for deployment scripts.
  • Example Use Case:
    • NTC’s Server Maintenance: Bash scripts restart services or clean up logs automatically.

Why Use Scripting Languages?

Scripting languages are essential for modern web development due to their flexibility and speed. Here’s why they’re preferred:

Advantages:

  1. Rapid Development:
    • No compilation step; changes are visible instantly (e.g., JavaScript in the browser).
  2. Platform Independence:
    • Run on any system with the interpreter (e.g., PHP on Windows/Linux).
  3. Integration:
    • Embedded in HTML (JavaScript) or used with web servers (PHP, Node.js).
  4. Dynamic Behavior:
    • Enable real-time updates (e.g., live chat, stock tickers).
  5. Automation:
    • Reduce manual work (e.g., Bash scripts for backups).

Disadvantages:

  1. Performance:
    • Slower than compiled languages (e.g., C++).
  2. Security Risks:
    • Vulnerable to injection attacks (e.g., SQL injection in PHP) if not sanitized.
  3. Debugging:
    • Runtime errors can be harder to trace than compile-time errors.

Scripting Languages in Action: A Worked Example

Let’s simulate a user registration system for a Nepalese e-commerce site (like Daraz) using both client-side (JavaScript) and server-side (PHP) scripting.

Scenario:

A user fills out a registration form with:

  • Name (required)
  • Email (must be valid)
  • Password (minimum 6 characters)

Step 1: HTML Form (Client-Side)

<form id="registerForm">
  <label>Name:</label>
  <input type="text" id="name" required>
  <label>Email:</label>
  <input type="email" id="email" required>
  <label>Password:</label>
  <input type="password" id="password" minlength="6" required>
  <button type="submit">Register</button>
</form>

Step 2: JavaScript Validation (Client-Side)

document.getElementById("registerForm").addEventListener("submit", function(event) {
  const name = document.getElementById("name").value;
  const email = document.getElementById("email").value;
  const password = document.getElementById("password").value;

  if (password.length < 6) {
    event.preventDefault();
    alert("Password must be at least 6 characters!");
  }
});

Step 3: PHP Processing (Server-Side)

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST["name"]);
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $password = password_hash($_POST["password"], PASSWORD_DEFAULT);

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die("Invalid email format!");
    }

    // Store in database (example)
    $conn = new mysqli("localhost", "user", "password", "ecommerce_db");
    $stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $name, $email, $password);
    $stmt->execute();
    echo "Registration successful!";
}
?>

Visual Trace: Data Flow

flowchart TD
    A["User fills form"] --> B["JavaScript validates password length"]
    B -->|"If invalid"| C["Show alert: 'Password too short!'"]
    B -->|"If valid"| D["Form submits to server"]
    D --> E["PHP receives data"]
    E --> F["Sanitize inputs (htmlspecialchars, filter_var)"]
    F --> G["Validate email format"]
    G -->|"Invalid"| H["Show error: 'Invalid email!'"]
    G -->|"Valid"| I["Hash password"]
    I --> J["Insert into MySQL database"]
    J --> K["Echo success message"]

State After Each Step:

  1. After JavaScript Validation:

    • If password were "123", the alert would block submission.
  2. After PHP Sanitization:

  3. After Database Insertion:


Exam Tip

This unit is theoretical but practical. Exams often test:

  1. Definitions: Differentiate between scripting and compiled languages, client-side vs. server-side.
  2. Use Cases: Explain where JavaScript or PHP would be used (e.g., "Why use JavaScript for form validation?").
  3. Code Snippets: Write short scripts (e.g., PHP form handling, JavaScript validation).
  4. Real-World Applications: Relate concepts to apps like eSewa, Daraz, or Pathao (e.g., "How does Pathao use AJAX?").
  5. Security: Mention risks like SQL injection or XSS and how to mitigate them (e.g., htmlspecialchars, password_hash).

Common Exam Questions and Answers:

Question Key Points to Include
"What is the difference between client-side and server-side scripting?" Client-side runs in browser (JavaScript), server-side runs on server (PHP).
"Why use both JavaScript and PHP in web development?" JavaScript for interactivity (e.g., validation), PHP for backend logic (e.g., DB).
"How does AJAX improve user experience?" Fetches data without page reload (e.g., live search, updates).
"Write a PHP script to validate a form." Use $_POST, filter_var, htmlspecialchars, and database insertion.
"What are the security risks of scripting languages?" SQL injection, XSS, CSRF. Mitigate with prepared statements, sanitization, and HTTPS.

Model Answer for a Past Exam Question:

Question: PHP and JavaScript are both programming languages that generate dynamic results for web pages. What is their main difference, and why would you use both of them?

Answer: The main difference between PHP and JavaScript lies in their execution environment and primary use cases:

Feature JavaScript PHP
Execution Client-side (browser) Server-side (web server)
Purpose Dynamic interactivity (DOM, events) Backend logic (database, security)
Example Use Validating a form before submission Processing the form and storing data
Syntax Runs in <script> tags in HTML Embedded in .php files

Why Use Both?

  1. Separation of Concerns:
    • JavaScript handles user-facing tasks (e.g., real-time validation, animations).
    • PHP handles server tasks (e.g., secure data processing, database operations).
  2. Performance:
    • JavaScript reduces server load by validating data in the browser.
    • PHP ensures security by processing data on the server (e.g., password hashing).
  3. User Experience:
    • JavaScript enables instant feedback (e.g., showing errors without reloading).
    • PHP generates dynamic content (e.g., personalized dashboards).

Example Workflow:

  1. User fills a registration form (HTML + JavaScript validates inputs).
  2. JavaScript submits data to PHP if valid.
  3. PHP sanitizes inputs, checks the database, and stores the user.

Summary

  • Scripting languages are interpreted, dynamic, and embedded in applications.
  • Client-side scripting (JavaScript) enables interactivity in browsers.
  • Server-side scripting (PHP, Python) processes data and interacts with databases.
  • Real-world apps like eSewa, Daraz, and Pathao rely on both for security, speed, and user experience.
  • Always sanitize inputs and validate data to prevent security vulnerabilities.

Visual Recap:

mindmap
  root((Scripting Languages in Web Dev))
    Client-Side (JavaScript)
      DOM Manipulation
      Event Handling
      AJAX for Real-Time Updates
    Server-Side (PHP/Python)
      Form Processing
      Database Interaction
      Security (e.g., Password Hashing)
    Real-World Examples
      eSewa: JavaScript + PHP for payments
      Daraz: JavaScript cart + PHP orders
      Pathao: JavaScript map + Python backend
    Key Concepts
      Interpreted Execution
      Embedded in HTML/Server
      Rapid Prototyping

Based on the TU BCA syllabus for Scripting Language (CACS254), unit 1.

Discussion

Loading…