Scripting LanguageUnit 1010 min read
jQuery UI & AJAX: Dynamic Web Interactions
Unit 10 of Scripting Language covers jQuery UI widgets (datepickers, sliders, dialogs), AJAX fundamentals (XMLHttpRequest, JSON), and real-world implementations like live form validation, asynchronous data loading, and seamless user experiences in apps like eSewa or Daraz.
TAKEAWAYS:
- jQuery UI provides ready-made interactive widgets (e.g., datepickers, accordions) that reduce JavaScript boilerplate by 70%.
- AJAX enables background server communication without page reloads, cutting perceived latency by 50% in apps like WhatsApp’s typing indicators.
- The
XMLHttpRequestobject handles HTTP requests asynchronously, while jQuery’s.ajax()simplifies syntax with built-in success/error callbacks. - JSON is the standard data format for AJAX responses, offering 90% smaller payloads than XML for the same data.
- Cross-origin restrictions (CORS) and security headers (CSRF tokens) are critical to prevent AJAX-based attacks like CSRF or XSS.
- Real-world examples show how AJAX powers live search (e.g., Daraz’s product filters) and dynamic content updates (e.g., Ncell’s balance checks).
1. jQuery UI: Interactive Widgets for Rich UX
jQuery UI extends jQuery with 12+ interactive widgets (e.g., datepickers, sliders, dialogs) built on top of jQuery’s core. These widgets reduce JavaScript code by 70% compared to vanilla JS implementations.
Key Widgets and Their Use Cases
mindmap
root((jQuery UI Widgets))
Datepicker["Datepicker: Input fields for dates/time (e.g., eSewa’s payment deadlines)"]
Slider["Slider: Range selectors (e.g., Daraz’s price filters)"]
Dialog["Dialog: Modal popups (e.g., Pathao’s order confirmations)"]
Accordion["Accordion: Collapsible sections (e.g., NTC’s service menus)"]
Autocomplete["Autocomplete: Live search suggestions (e.g., Google Maps)"]
Progressbar["Progressbar: Visual feedback (e.g., file uploads)"]Example: Datepicker in eSewa’s Bill Payment
Scenario: Users must select a due date for utility bills (e.g., NTC or Ncell). A datepicker ensures valid input and improves UX.
<!-- HTML -->
<input type="text" id="dueDate" name="dueDate">
<!-- jQuery UI Script -->
<script>
$(function() {
$("#dueDate").datepicker({
minDate: 0, // No past dates
maxDate: "+30d", // Max 30 days ahead
dateFormat: "yy-mm-dd",
onSelect: function(dateText) {
alert("Selected date: " + dateText); // Simulate validation
}
});
});
</script>
Visual: Datepicker After Selection
Advantages of jQuery UI
| Feature | Benefit |
|---|---|
| Pre-built | No need to write custom JS for common UI elements. |
| Theming | Supports CSS themes (e.g., ui-lightness, ui-darkness). |
| Accessibility | WCAG-compliant widgets (e.g., keyboard-navigable datepickers). |
| Performance | Optimized for mobile/desktop; reduces DOM manipulation overhead. |
2. AJAX: Asynchronous Data Exchange
AJAX (Asynchronous JavaScript and XML) enables background HTTP requests without reloading the page. Used in:
- Live search (e.g., Daraz’s product filters).
- Dynamic updates (e.g., WhatsApp’s "typing..." indicators).
- Form validation (e.g., eSewa’s phone number checks).
How AJAX Works
sequenceDiagram
User->>Browser: Triggers AJAX request (e.g., clicks "Check Availability")
Browser->>Server: Sends HTTP request (XMLHttpRequest or Fetch API)
Server-->>Browser: Returns JSON/XML response
Browser->>User: Updates UI without reload (e.g., shows "Available" or "Taken")XMLHttpRequest vs. jQuery’s .ajax()
| Feature | XMLHttpRequest | jQuery .ajax() |
|---|---|---|
| Syntax | Verbose (10+ lines of code) | Concise (5 lines max) |
| Error Handling | Manual checks (status, readyState) |
Built-in error() callback |
| Data Types | Supports XML, JSON, text | Auto-detects content type |
| Browser Support | Legacy (IE7+) | Modernized; polyfills included |
Example: Phone Availability Check (e.g., eSewa Signup)
Scenario: Validate if a phone number exists in the database before signup.
// Vanilla JS (XMLHttpRequest)
function checkPhoneAvailability(phone) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "check_phone.php?phone=" + phone, true);
xhr.onload = function() {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
if (response.available) {
document.getElementById("signupBtn").disabled = false;
} else {
alert("Phone already registered!");
}
}
};
xhr.send();
}
// jQuery AJAX (Simplified)
function checkPhoneAvailabilityJQ(phone) {
$.ajax({
url: "check_phone.php",
type: "GET",
data: { phone: phone },
success: function(response) {
if (response.available) {
$("#signupBtn").prop("disabled", false);
} else {
alert("Phone already registered!");
}
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
}
Trace: Variable States During AJAX Request
| Step | xhr.readyState |
xhr.status |
responseText |
UI Update |
|---|---|---|---|---|
| Initial | 0 (UNSENT) | - | - | Button disabled |
After open() |
1 (OPENED) | - | - | - |
After send() |
2 (SENT) | - | - | Loading spinner |
| Server Response | 3 (LOADING) | 200 | {"available":false} |
- |
| Complete | 4 (DONE) | 200 | {"available":false} |
Alert: "Phone taken!" |
3. Real-World Applications
Example 1: Daraz’s Live Search (AJAX + Autocomplete)
- Idea Used: AJAX + jQuery UI’s
autocomplete(). - How It Works:
- User types in the search box (e.g., "iPhone").
- AJAX sends a request to Daraz’s backend with the partial query.
- Server returns JSON:
["iPhone 15", "iPhone 14 Pro", "iPhone SE"]. - jQuery populates the dropdown without page reload.
- Code Snippet:
$(function() { $("#searchInput").autocomplete({ source: function(request, response) { $.ajax({ url: "search_products.php", data: { term: request.term }, success: function(data) { response(data.products); // JSON array of matches } }); }, minLength: 2 }); });
Example 2: Ncell’s Balance Check (AJAX)
- Idea Used: AJAX + JSON response.
- How It Works:
- User enters phone number and clicks "Check Balance".
- AJAX sends the number to Ncell’s API (
/api/balance?phone=98XXXXXXXX). - Server returns:
{"balance": 500, "currency": "NPR"}. - jQuery updates the UI dynamically.
- Visual: Before/After AJAX Response
Example 3: eSewa’s Payment Deadline (jQuery UI Datepicker)
- Idea Used: jQuery UI’s
datepicker(). - How It Works:
- User selects a bill due date (e.g., NTC electricity).
- Datepicker enforces:
- No past dates (
minDate: 0). - Max 30 days ahead (
maxDate: "+30d").
- No past dates (
- On selection, eSewa calculates late fees if applicable.
- Code:
$("#dueDate").datepicker({ dateFormat: "yy-mm-dd", beforeShowDay: function(date) { var day = date.getDay(); return [day !== 0, ""]; // Disable Sundays } });
4. Security and Best Practices
Common AJAX Vulnerabilities
| Vulnerability | Risk | Mitigation |
|---|---|---|
| CSRF | Fake requests via stolen cookies | Use CSRF tokens in AJAX headers. |
| XSS | Malicious scripts in responses | Sanitize JSON responses (e.g., htmlspecialchars() in PHP). |
| SQL Injection | User input in SQL queries | Use prepared statements (PDO). |
| Data Leakage | Sensitive data in URLs | Use POST instead of GET. |
Best Practices
- Always validate server-side: Never trust client-side AJAX responses.
- Use HTTPS: Encrypt all AJAX traffic (e.g., eSewa’s payment pages).
- Handle errors gracefully:
$.ajax({ error: function(xhr, status, error) { if (status === "timeout") { $("#error").text("Server took too long. Retry."); } } }); - Cache responses: Reduce server load with
cache: true(e.g., Daraz’s product filters).
5. jQuery UI vs. Vanilla JS: Comparison
| Feature | jQuery UI | Vanilla JS |
|---|---|---|
| Code Length | 3–5 lines | 20–50 lines |
| Browser Support | Polyfills included | Manual checks needed |
| Theming | Built-in (e.g., ui-lightness) |
Custom CSS required |
| Learning Curve | Steeper (requires jQuery knowledge) | Easier for beginners |
| Performance | Slightly slower (abstraction layer) | Faster (direct DOM manipulation) |
When to Use Which?
- Use jQuery UI for rapid prototyping (e.g., student projects).
- Use Vanilla JS for high-performance apps (e.g., games, large-scale SPAs).
Exam Tip
For jQuery UI:
- Memorize 3 widgets (e.g., datepicker, slider, dialog) and their 2 key options each.
- Example:
datepicker({ minDate: 0, dateFormat: "yy-mm-dd" }). - Common Exam Question: Write code to add a datepicker to an input field.
For AJAX:
- Syntax: Know both
XMLHttpRequestand jQuery’s.ajax(). - Flow: Draw the sequence diagram (browser → server → browser).
- Example: Phone availability check (as shown above).
- Security: Mention CSRF tokens and HTTPS in answers.
- Syntax: Know both
Real-World Tie-Ins:
- Relate AJAX to eSewa’s live balance checks or Daraz’s search.
- For jQuery UI, mention Ncell’s service menus (accordion) or Pathao’s dialogs.
Avoid These Mistakes:
- Forgetting to handle
errorcallbacks in AJAX. - Not setting
async: false(deprecated; use promises instead). - Ignoring CORS errors in cross-domain requests.
- Forgetting to handle
Final Note: Focus on practical examples (like the phone check or datepicker) and visual traces (e.g., readyState table). Examiners love step-by-step explanations with before/after diagrams!
Based on the TU BCA syllabus for Scripting Language (CACS254), unit 10.
Discussion
Loading…