Xtreme-jQuery: two small, inspectable utilities

This page publishes two original helper functions for projects that already load jQuery. They are intentionally small examples, not a packaged framework or a promise of support. Read the source, check the behaviour in your own application, and keep server-side validation and security controls where they belong.

Download the source file or review the functions below. Load jQuery before this file.

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="/xtreme-jquery.js"></script>

Function overview

Generate a random string

$.rand() defaults to 16 characters from letters and digits. Supply a custom alphabet when a downstream format requires one. It uses unbiased rejection sampling with crypto.getRandomValues(); it throws when the browser does not provide Web Crypto rather than silently falling back to the predictable Math.random(). This helper only generates bytes for a string. It does not protect a secret after creation or replace an application’s complete password, token, or key-management design.

var reference = $.rand(12);
var hexCode = $.rand(16, "0123456789abcdef");

Send JSON with $.postJSON

$.postJSON() serializes an object as a JSON request body and asks jQuery to parse a JSON response. The optional callback runs on success; the returned jqXHR supports .fail() and other Deferred methods. Your server must accept JSON and validate every field. For state-changing requests, use the anti-CSRF protection required by your application.

$.postJSON("/api/items", { name: "Example" }, function (result) {
  $("#status").text("Saved: " + result.id);
}).fail(function (xhr) {
  $("#status").text("The request could not be saved.");
});

Source and compatibility

The downloadable file is the source shown on this page. It attaches the helpers to the jQuery object, so load it after jQuery. The JSON helper relies on $.ajax(); the random-string helper requires a secure context with the Web Crypto API. The functions are deliberately not minified so they can be inspected and adapted.