JavaScript API for themes and modules
Every admin and client area page loads a small JavaScript runtime. Your theme or module uses it to call the API from the browser with the visitor’s session, and to show messages the same way ClientFence does. What a call sends and answers is in Requests and responses; this page covers the browser side.
What each page loads
Section titled “What each page loads”| File | Loaded in | What it gives you |
|---|---|---|
public/assets/js/clientfence.js |
Admin and client area | ClientFence.ready(), ClientFence.ui.notify(), cookies, ClientFence.currency.format(), ClientFence.editor |
public/assets/js/api.js |
Admin and client area | ClientFence.api, ClientFence.tools, and the data-fb-api forms and links |
public/assets/css/loader.css |
Admin and client area | The style of the loading card shown during a call |
Admin theme scripts (build/js/clientfence.js, clientfence/clientfence-admin.js) |
Admin area | ClientFence.message() toasts, the Modals dialogs, bootstrap |
Palisade script (build/js/palisade.js) |
Client area | ClientFence.message() toasts, flashMessage(), bootstrap |
The two shared scripts run in the <head>, so ClientFence.api exists as soon as your script runs. The
theme scripts are modules and run after the page is parsed. Wrap code that needs the page or
ClientFence.message() in ClientFence.ready(): it runs once the page is ready, or at once if it
already is.
A theme of your own keeps the clientfence.js, loader.css and api.js lines in its head (see
Create your own client theme). Without a theme
script that defines ClientFence.message(), messages only go to the browser console.
Call the API
Section titled “Call the API”ClientFence.api.<role>.<method>(call, params, onSuccess, onError, showLoader);| Part | What it is |
|---|---|
role |
client, guest or admin. |
method |
post, get, put, patch or delete. ClientFence’s own scripts use post. |
call |
<module>/<call>, for example profile/get or invoice/mass_pay. |
params |
An object (sent as JSON), a FormData, or nothing. |
onSuccess(result) |
Gets the result field of the answer. |
onError(error) |
Gets { message, code }. |
showLoader |
true by default: a loading card shows in the middle of the page if the call takes longer than a quarter of a second. It does not block clicks. Pass false for background calls. |
The call runs with the browser’s session: a client call as the signed-in client, an admin call as
the signed-in staff member. A call times out after 30 seconds.
The post, get and the other methods return nothing, so use the two callbacks. To await a call,
wrap it in a promise, as Palisade does:
const api = (role, call, params = {}) => new Promise((resolve, reject) => { ClientFence.api[role].post(call, params, resolve, reject, false);});A read call
Section titled “A read call”This fills an element with the client’s balance, without the loading card:
<p data-mybrand-balance></p>ClientFence.ready(() => { const box = document.querySelector('[data-mybrand-balance]'); if (!box) { return; } ClientFence.api.client.post('profile/get', {}, (profile) => { if (profile.currency) { box.textContent = ClientFence.currency.format(profile.balance, { code: profile.currency }); } }, (error) => { ClientFence.message(error.message, 'error'); }, false);});A change call
Section titled “A change call”This button makes a new Support PIN and shows it. The button is disabled while the call runs, so a double click sends one request:
<button type="button" class="btn btn-primary" data-mybrand-new-pin>New PIN</button><strong data-mybrand-pin></strong>ClientFence.ready(() => { document.querySelectorAll('[data-mybrand-new-pin]').forEach((button) => { button.addEventListener('click', () => { button.disabled = true; ClientFence.api.client.post('client/support_pin_new', {}, (pin) => { button.disabled = false; document.querySelector('[data-mybrand-pin]').textContent = pin; ClientFence.message('A new PIN was made.', 'success'); }, (error) => { button.disabled = false; ClientFence.message(error.message, 'error'); }); }); });});Put text into the page with textContent, never innerHTML: API answers can hold what clients typed.
Errors
Section titled “Errors”onError gets an object with message and code:
code |
When |
|---|---|
| The API’s error code | The answer has an error, for example 9999 or 403 (CSRF token invalid). See Errors. |
http_<status> |
The server answered an HTTP error without an API error, for example http_500. |
timeout_error |
No answer after 30 seconds. |
network_error |
The browser could not reach the server. |
unknown_error |
Anything else, such as an answer that is not JSON. |
Show error.message with ClientFence.message(error.message, 'error'). A call without onError still
shows its error as a toast in the admin area and in Palisade.
On a signed-in page, a client or admin call that answers Authentication Failed means the session
ended. If nothing was typed on the page, the page reloads, which leads to the sign-in page. If something
was typed, nothing reloads: onError gets a message that asks to copy the text and sign in again.
The CSRF token
Section titled “The CSRF token”You do not add it yourself. When a page is shown, ClientFence sets the session’s token in the
clientfence_csrf cookie. ClientFence.api reads it and sends it as the X-CSRF-Token header, and for
a post also as the CSRFToken parameter when the parameters are an object or FormData. The token goes only to your own
site’s address, never to another website.
A client or admin call with a missing or wrong token answers CSRF token invalid. So do the
guest calls that sign in or change the cart; those also need post.
For a request with fetch() instead of the helper:
const answer = await fetch('/api/client/profile/get', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': ClientFence.tools.getCSRFToken() ?? '', }, body: '{}',}).then((response) => response.json());if (answer.error) { ClientFence.message(answer.error.message, 'error');}A plain HTML form that posts to a page of your own can carry the token from Twig:
<input type="hidden" name="CSRFToken" value="{{ CSRFToken }}">.
Forms and links without code
Section titled “Forms and links without code”A form or link with a data-fb-api attribute calls the API in the background. Write the attribute
with the Twig functions fb_api_form() and fb_api_link(), and the call’s address with api_url
(see Twig filters, functions and variables):
<form action="{{ 'client/balance_alert_save'|api_url }}" {{ fb_api_form({ message: 'Saved'|trans }) }}> … <button type="submit" class="btn btn-primary">{{ 'Save'|trans }}</button></form>
<a href="{{ 'client/support_pin_new'|api_url }}" {{ fb_api_link({ modal: { type: 'confirm', title: 'Make a new Support PIN?'|trans, content: 'The current PIN stops working.'|trans }, reload: true }) }}> {{ 'New PIN'|trans }}</a>api_url uses the role of the area you are in; add role: 'guest' for a guest call, for example
'client/login'|api_url(role: 'guest').
A form sends its fields as JSON to its action, with the clicked button’s name and value. Its
buttons are disabled until the answer comes. A form without action sends nothing.
A link sends a get request to its href (or to the href key of the config). Only <form> and
<a> elements are handled; a data-fb-api attribute on a <button> does nothing.
After a successful call, the first matching key decides what happens:
| Key | What happens |
|---|---|
callback |
Calls the global function with this name with the result, and nothing else. Define it in a script with the nonce. |
redirect |
Opens this address. The message, if any, shows on the next page. |
reload |
true: reloads the page. The message, if any, shows after the reload. |
message |
Shows this text as a success toast. |
| (none) | Shows a success toast Form Updated. In the admin area, a form that reloads or redirects without a message shows Changes saved on the next page, a link Done. |
An error shows its message as an error toast, and the form or link can be used again.
Keys for links only:
| Key | What it does |
|---|---|
modal |
Asks first. type: confirm, danger or prompt; title, content, button (the confirm button’s text) and buttonColor. A prompt asks for a value and sends it as the parameter named in key, with label and value for the field. In the client area, Palisade asks with the browser’s own confirm and prompt boxes. |
params |
Extra parameters sent with the call, as an object. |
loading |
While the call runs: button replaces the link text and adds a spinner, message shows a note under the link (target: a CSS selector for where, alertClass: its classes). |
preventNavigation |
true: the browser asks before the visitor leaves the page during the call. |
timeoutMs, timeoutMessage |
A longer or shorter time limit than 30 seconds, and the text shown when it runs out. |
In Palisade, a form with data-clientfence-confirm="Your question?" asks that question in a confirm
box before it is sent.
Toasts, saved messages and dialogs
Section titled “Toasts, saved messages and dialogs”ClientFence.message(text, type): a toast.typeissuccess,error,warningorinfo. The text is shown as plain text. Errors stay 8 seconds, the others 5. The page needs an element with the classtoast-container, which both shipped themes have.ClientFence.ui.notify(text, type): the same, but writes to the console if no theme script definedClientFence.message(). Use it in a module that may run under someone else’s theme.flashMessage({ message, reload })(client area only): keeps a message for the next page.reload: truereloads at once, a string opens that address. Call it from a click or a callback.Modals.create({ type, title, content, confirmButton, confirmCallback })(admin area only): a dialog.typeisdefault,small,small-confirm,danger,successorprompt.titleandcontentare inserted as HTML: escape any text that is not yours.
Toast texts that ClientFence itself shows in English are translated from the page’s
#clientfence-i18n texts. Translate your own texts in Twig with |trans and pass them to your script,
for example in a data- attribute.
Other helpers
Section titled “Other helpers”| Helper | What it does |
|---|---|
ClientFence.ready(fn) |
Runs fn when the page is ready, or at once if it already is. |
ClientFence.currency.format(amount, { code }, locale) |
An amount with its currency sign, for example $12.50. |
ClientFence.cookieRead(name), ClientFence.cookieCreate(name, value, days) |
Reads and sets a cookie for the whole site. |
ClientFence.detectTimezone() |
The browser’s time zone, such as Europe/Berlin, or null. |
ClientFence.tools.getCSRFToken() |
The session’s CSRF token. |
ClientFence.tools.serializeFormDataToObject(formData) |
A FormData as an object: ids[] becomes a list, a[b] a nested object. Adds the CSRF token. |
ClientFence.editor.get(name) |
The rich text editor of the field with this name (getData(), setData()), made with the wysiwyg Twig function. |
Ship your own script
Section titled “Ship your own script”Every page sends a script policy (Content Security Policy): a <script> runs only with this page’s
nonce, and onclick and other on… attributes never run. Put your code in a file, attach events with
addEventListener, and load the file with script_tag, which adds the nonce:
| Where the file is | Load it with |
|---|---|
A theme: themes/mybrand/assets/js/mybrand.js |
{{ 'js/mybrand.js'|asset_url|script_tag }} in partials/head.html.twig |
A module: modules/Hello/assets/hello.js |
{{ 'hello.js'|mod_asset_url('hello')|script_tag }} in the module’s template |
In a module template, put the tag in {% block js %}. In Palisade that block is in the <head>, so wrap
your code in ClientFence.ready(). A short script can also stay in the template:
<script nonce="{{ csp_nonce }}">…</script>. Pass data from Twig in a JSON block that the script
reads:
<script nonce="{{ csp_nonce }}" type="application/json" id="mybrand-data">{{ { invoice: invoice.hash }|json_encode|raw }}</script>const data = JSON.parse(document.getElementById('mybrand-data').textContent);More on the policy: Follow the script policy. Blocked scripts show in System Health (see System health).

