Skip to content

Commit ec4a3f4

Browse files
committed
Enhance JavaScript Patterns documentation with additional explanations on AJAX form submission, SweetAlert usage, dynamic content loading, error handling, and user input handling for improved clarity and usability.
1 parent e530122 commit ec4a3f4

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

docs/ui/javascript-patterns.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ Unraid includes these JavaScript libraries by default:
2020

2121
## AJAX Form Submission
2222

23+
Use jQuery's `$.post()` method to submit forms without a full page reload. This pattern intercepts the form's submit event, serializes the form data, and sends it to your PHP handler. The response can be JSON for programmatic handling or trigger a page reload on success.
24+
2325
```javascript
2426
$(function() {
2527
$('#myForm').on('submit', function(e) {
@@ -40,6 +42,8 @@ $(function() {
4042

4143
## Saving Settings with $.post()
4244

45+
For simpler cases where you don't need form serialization, you can build the POST data object manually. This is useful when saving individual settings or triggering actions from buttons rather than forms. Always include the CSRF token for security.
46+
4347
```javascript
4448
function saveSettings() {
4549
$.post('/update.php', {
@@ -56,13 +60,17 @@ function saveSettings() {
5660

5761
### Simple Alert
5862

63+
The simplest form of SweetAlert takes three arguments: title, message, and type. Use this for quick notifications that don't require user input or confirmation.
64+
5965
```javascript
6066
swal('Title', 'Message text', 'info');
6167
// Types: 'success', 'error', 'warning', 'info'
6268
```
6369

6470
### Confirmation Dialog
6571

72+
Use confirmation dialogs before destructive actions like deletion or irreversible changes. The callback receives `true` if the user confirmed, allowing you to proceed with the action only after explicit approval.
73+
6674
```javascript
6775
swal({
6876
title: 'Are you sure?',
@@ -80,6 +88,8 @@ swal({
8088

8189
### Input Dialog
8290

91+
Input dialogs collect a single text value from the user. The callback receives `false` if cancelled, an empty string if submitted empty, or the actual input value. Use `swal.showInputError()` to display validation errors without closing the dialog.
92+
8393
```javascript
8494
swal({
8595
title: 'Enter value',
@@ -98,6 +108,8 @@ swal({
98108

99109
## Dynamic Content Loading
100110

111+
Load content dynamically via AJAX to update portions of the page without a full reload. This pattern is useful for status displays, logs, or any content that changes frequently. Use `setInterval()` for automatic refresh, but remember to clear the interval when the page unloads.
112+
101113
```javascript
102114
function loadStatus() {
103115
$.get('/plugins/yourplugin/status.php', function(html) {
@@ -111,6 +123,8 @@ setInterval(loadStatus, 5000);
111123

112124
## Toggle Visibility
113125

126+
Conditionally show or hide form sections based on user selections. This improves UX by hiding irrelevant options. The `.trigger('change')` call at the end ensures the correct visibility state is set when the page first loads, not just when the user changes the value.
127+
114128
```javascript
115129
// Show/hide based on select value
116130
$('#enableFeature').on('change', function() {
@@ -124,6 +138,8 @@ $('#enableFeature').on('change', function() {
124138

125139
## Inline Script in Page Files
126140

141+
Page files can mix PHP and JavaScript, allowing you to inject server-side values into your client-side code. Use `addslashes()` when outputting PHP strings into JavaScript to prevent quote characters from breaking your code. The CSRF token is accessed from the `$var` superglobal.
142+
127143
```php
128144
<?
129145
// Your PHP code
@@ -147,6 +163,8 @@ $(function() {
147163

148164
## Event Handlers
149165

166+
These are the most common jQuery event patterns you'll use in Unraid plugins. The document ready handler ensures DOM elements exist before your code runs. Use `.on()` for event binding as it's the modern jQuery approach and supports event delegation.
167+
150168
```javascript
151169
// Document ready
152170
$(function() {
@@ -168,6 +186,8 @@ $('input, select').on('change', function() {
168186

169187
## Error Handling
170188

189+
Always handle AJAX errors gracefully. Network failures, server errors, and timeouts can all occur. The `$.ajax()` method provides an `error` callback for these cases. Display user-friendly error messages rather than exposing technical details.
190+
171191
```javascript
172192
$.ajax({
173193
url: '/plugins/yourplugin/action.php',
@@ -186,6 +206,8 @@ $.ajax({
186206

187207
### Simple Loading Spinner
188208

209+
Provide visual feedback during AJAX operations so users know something is happening. A simple spinner or "Loading..." message prevents users from clicking repeatedly or thinking the UI is broken.
210+
189211
```javascript
190212
// Show loading state
191213
function showLoading(container) {
@@ -205,6 +227,8 @@ $.get('/plugins/yourplugin/status.php', function(data) {
205227

206228
### Progress Bar
207229

230+
For operations with measurable progress (file uploads, batch processing), a progress bar provides better feedback than a spinner. This example includes both a visual bar and text percentage. The CSS transition creates smooth animation as the bar width changes.
231+
208232
```html
209233
<div id="progress-container" style="display:none;">
210234
<div class="progressbar">
@@ -243,6 +267,8 @@ function hideProgress() {
243267

244268
### Long-Running Task with Progress
245269

270+
For server-side tasks that take significant time (backup, conversion, download), use a polling pattern. Start the task and receive a task ID, then periodically query the server for progress updates. This avoids HTTP timeouts and provides real-time feedback.
271+
246272
```javascript
247273
function startLongTask() {
248274
updateProgress(0, 'Starting...');
@@ -278,6 +304,8 @@ SweetAlert is included in Unraid and provides attractive modal dialogs.
278304

279305
#### Basic Alerts
280306

307+
SweetAlert provides more attractive and customizable alerts than the browser's native `alert()` function. The type parameter controls the icon displayed: success (green checkmark), error (red X), warning (yellow exclamation), or info (blue i).
308+
281309
```javascript
282310
// Simple alert
283311
swal('Title', 'Message text', 'info');
@@ -294,6 +322,8 @@ swal({
294322

295323
#### Confirmation Dialog
296324

325+
Require explicit user confirmation before destructive operations. The red confirm button color (`#d33`) signals danger. Customize button text to clearly describe what will happen ("Yes, delete it!" is clearer than "OK").
326+
297327
```javascript
298328
swal({
299329
title: 'Are you sure?',
@@ -312,6 +342,8 @@ swal({
312342

313343
#### Input Dialog
314344

345+
Collect user input inline without navigating to a separate form. The `inputValue` option pre-fills the field with a default. Handle three cases: cancelled (false), empty string, or valid input. Use `swal.showInputError()` for inline validation without closing the dialog.
346+
315347
```javascript
316348
swal({
317349
title: 'Enter Name',
@@ -333,6 +365,8 @@ swal({
333365

334366
#### HTML Content Dialog
335367

368+
Enable the `html: true` option to render HTML markup in the dialog body. This allows formatted content like tables, lists, or styled text. Be cautious with user-provided content—sanitize it to prevent XSS attacks.
369+
336370
```javascript
337371
swal({
338372
title: 'Details',
@@ -346,6 +380,8 @@ swal({
346380

347381
#### Loading Dialog
348382

383+
Display a modal loading indicator during async operations to prevent user interaction. Disable the confirm button and outside clicks to keep users from dismissing it prematurely. Call `swal.close()` when the operation completes.
384+
349385
```javascript
350386
// Show loading
351387
swal({
@@ -363,6 +399,8 @@ doAsyncTask().then(function() {
363399

364400
### Custom Modal
365401

402+
When SweetAlert doesn't meet your needs (complex forms, rich content, custom layouts), build a custom modal. This pattern includes the overlay background, close button, escape key handling, and click-outside-to-close behavior that users expect from modal dialogs.
403+
366404
```html
367405
<!-- Modal HTML -->
368406
<div id="myModal" class="modal" style="display:none;">
@@ -429,6 +467,8 @@ Unraid includes `dynamix.js` with useful utilities:
429467

430468
### Common Functions
431469

470+
Unraid's `dynamix.js` provides utility functions for common operations. These handle locale-aware number formatting and file size display, ensuring consistency with the rest of the Unraid UI. Use these instead of writing your own formatting code.
471+
432472
```javascript
433473
// Format file size
434474
var size = my_scale(bytes); // Returns "1.5 GB" etc.
@@ -447,6 +487,8 @@ function done() {
447487

448488
### Refresh and Reload
449489

490+
Unraid provides a `refresh()` function for updating specific page sections without a full reload. For complete page refreshes, use the standard `location.reload()`. Pass `true` to force a cache-clearing reload when you need the latest server content.
491+
450492
```javascript
451493
// Refresh specific section
452494
function refresh(section) {
@@ -464,6 +506,8 @@ location.reload(true);
464506

465507
### Basic Shortcuts
466508

509+
Add keyboard shortcuts for power users. Common conventions include Ctrl+S to save and Escape to close/cancel. Always call `e.preventDefault()` to stop the browser's default behavior (Ctrl+S normally opens a "Save Page" dialog).
510+
467511
```javascript
468512
$(document).on('keydown', function(e) {
469513
// Ctrl+S to save
@@ -620,6 +664,8 @@ $('#container').html('<span class="error">' + escapeHtml(errorMessage) + '</span
620664

621665
### Preventing Double-Submit
622666

667+
Prevent users from accidentally submitting a form multiple times by clicking rapidly or pressing Enter repeatedly. This pattern disables the submit button after the first click and uses a data attribute to track submission state.
668+
623669
```javascript
624670
$('#myForm').on('submit', function(e) {
625671
var $button = $(this).find('input[type="submit"]');
@@ -633,6 +679,8 @@ $('#myForm').on('submit', function(e) {
633679

634680
### Debouncing Input
635681

682+
Debouncing delays execution until the user stops typing, preventing excessive API calls on every keystroke. The 300ms delay is a good balance—short enough to feel responsive, long enough to avoid firing during normal typing. Clear the previous timer on each keystroke to reset the delay.
683+
636684
```javascript
637685
var debounceTimer;
638686
$('#searchInput').on('input', function() {

0 commit comments

Comments
 (0)