Documentation

On this page

Download full book (text)

# **Chapter 25: React and Vite Client — Calling Gates from a SPA** > **Prerequisites:** Chapter 13 (AJAX / jsServer), Chapters 5–6 (FrontFiles), > Chapter 17 (form components / fui validation) > **Try it:** Gate `exreactajax` > (`apps/examples/ExReactAjax.gate.php` + fronts under `apps/examples/fronts/exreactajax_*.front`). > Client library: `comp/reactJs/` (this site or your app). > `baseUrl`: your SartajPhp website origin (any app with Gates). > **Run:** [exreactajax.html](exreactajax.html) --- ## **25.1 Why a Separate React Client** Classic SartajPhp pages load `ajax.js` (jQuery) and call `sendAjax` / `getAjaxReturn` / `callNativeGate`. A **Vite + React** app does not use that stack — it owns the UI, while SartajPhp still owns Gates, FrontFiles, and jsServer responses. The bridge is a small ESM client that keeps the **same API names** as `ajax.js`: | Classic (`ajax.js`) | React client (`sphp-client.js`) | |---------------------|----------------------------------| | `sendAjax(url, data)` | `sphp.sendAjax(url, data)` | | `getAjaxReturn(url, data, raw, cb)` | `sphp.getAjaxReturn(url, data, raw, cb)` | | `callNativeGate(gate, evt, evtp, data)` | `sphp.callNativeGate(gate, evt, evtp, data)` | **Rule of ownership** - **React** — layout, state, buttons, slots - **SartajPhp Gate** — `page_event_*`, `jsServer` blocks, FrontFiles, fui validation - **Do not** redesign React widgets as FrontFile components unless you intentionally inject a Front with `addJsonFront` (forms, panels) ## **25.2 Two URLs — Client Library vs Your App** Keep these separate: | Setting | What it is | |---------|------------| | **Client files** (`sphp-client.js`, …) | Shared library. Published under `comp/reactJs/` on this docs site so you can import or copy them. You may also ship the same folder inside **your** SartajPhp project. | | **`baseUrl`** | Origin of **any SartajPhp website** that hosts your Gates (`start.php` + `reg.php`). That is usually **your** app, not the framework docs host. | | Path under a SartajPhp site root | Role | |----------------------------------|------| | `comp/reactJs/sphp-client.js` | ESM client (fetch + jsServer parser) | | `comp/reactJs/sphp-react.jsx` | Optional `SphpSlot` / `useSphpHtml` | | `comp/reactJs/README.md` | Short API notes | **Ways to get the client** 1. **Import from this docs site’s** `comp/reactJs/` (easy updates when the library changes). 2. **Copy** `comp/reactJs/` into your SPA or into your own SartajPhp project and serve it from there. 3. **Local clone only for maintainers** — optional; see §25.12. **`baseUrl` always points at the SartajPhp app you call** (demo Gates on this site, or production Gates on your domain). ## **25.3 Step 1 — Register the Demo Gate (in your SartajPhp app)** ```php <?php // reg.php registerGate("exreactajax", __DIR__ . "/apps/examples/ExReactAjax.gate.php"); ``` On this site the demo is already registered. Open `exreactajax.html`. AJAX endpoints: `exreactajax-ping.html`, `exreactajax-echo.html`, `exreactajax-panel.html`, `exreactajax-form.html`, `exreactajax-save.html`. ## **25.4 Step 2 — Vite: Client Alias** Alias the shared client (from this docs site, or from `comp/reactJs/` on **your** SartajPhp site if you copied the folder there): ```js import react from '@vitejs/plugin-react' import { defineConfig } from 'vite' // Where you load the shared client FROM (docs site or your app that ships comp/reactJs/) const SPHP_CLIENT_ORIGIN = 'https://sartajphp.com' // Example if you host the client on your own app instead: // const SPHP_CLIENT_ORIGIN = 'https://myapp.example' export default defineConfig({ plugins: [react()], resolve: { alias: { 'sphp-client': SPHP_CLIENT_ORIGIN + '/comp/reactJs/sphp-client.js', 'sphp-react': SPHP_CLIENT_ORIGIN + '/comp/reactJs/sphp-react.jsx', }, }, server: { port: 5173, }, }) ``` If your bundler dislikes remote JSX, download the two files into e.g. `src/vendor/sphp/` and alias to those copies instead. ## **25.5 Step 3 — Configure `baseUrl` to Your SartajPhp Site** `baseUrl` is the origin of **the SartajPhp website that runs your Gates** — any project with `start.php`, not specifically the framework docs host. ```js import sphp from 'sphp-client' import { SphpSlot } from 'sphp-react' sphp.configure({ // YOUR SartajPhp app (Gates live here). Examples: // 'https://myapp.example' // 'https://sartajphp.com' // only when calling Gates on this docs demo site baseUrl: 'https://myapp.example', credentials: 'include', debug: true, }) // Optional: Gate callJsFunction('onAjaxPing', msg) window.onAjaxPing = function (msg) { console.log('onAjaxPing', msg) } sphp.sendAjax('exreactajax-ping.html', { txtname: 'Ada' }) sphp.getAjaxReturn('exreactajax-echo.html', { txt: 'hi' }, true, (retobj) => { console.log(retobj) }) ``` `baseUrl` prefixes every Gate path, so `exreactajax-echo.html` is requested on **that** app. `ensureFormLibs()` loads jQuery / jslib / `validation.js` from the same `baseUrl` origin (so that app must expose the usual vendor assets). Status HTML from the Gate: ```jsx <SphpSlot id="sphpStatus" className="status" fallback="idle" /> ``` > **CORS:** if the SPA origin differs from `baseUrl`, the SartajPhp app (or its > reverse proxy) must allow your SPA origin and credentials. Same-origin hosting > needs no extra CORS. ## **25.6 Gate: ping / echo / panel / form / save** Full tested Gate (`apps/examples/ExReactAjax.gate.php`): ```php <?php /** * React / Vite client test Gate — jsServer responses for sphp-client.js * Registered as gate "exreactajax" in reg.php. */ use Sphp\Gates\BasicGate; use Sphp\Tools\FrontFile; class ExReactAjax extends BasicGate { private $frtMain = null; private $frtPanel = null; private $frtForm = null; public function onstart() { global $masterf; $this->frtMain = new FrontFile('main'); $this->frtPanel = new FrontFile('panel'); $this->frtForm = new FrontFile('form'); $this->setMasterFile($masterf); } public function page_new() { $this->setFrontFile($this->frtMain); } /** sendAjax — HTML + callJsFunction */ public function page_event_ping($evtp) { $name = trim((string) $this->client->request('txtname')); if ($name === '') { $name = 'React'; } $msg = 'Pong ' . $name . ' @ ' . date('H:i:s'); $this->jsServer->addJsonHtmlBlock('sphpStatus', $msg); $this->jsServer->callJsFunction('onAjaxPing', $msg . ' test from sartajphp'); } /** getAjaxReturn — structured retobj */ public function page_event_echo($evtp) { $text = trim((string) $this->client->request('txt')); if ($text === '') { $text = '(empty)'; } $this->jsServer->addJsonHtmlBlock('sphpStatus', 'Echo OK via jsServer'); $this->jsServer->addJsonReturnBlock(array( 'ok' => true, 'echo' => $text, 'source' => 'exreactajax', 'at' => date('c'), )); } /** addJsonFront — panel FrontFile into #sphpPanel */ public function page_event_panel($evtp) { $who = trim((string) $this->client->request('who')); if ($who === '') { $who = 'guest'; } $this->frtPanel->spnPanelTitle->setInnerHTML('Front via addJsonFront'); $this->frtPanel->spnPanelBody->setInnerHTML( 'Hello ' . htmlspecialchars($who, ENT_QUOTES, 'UTF-8') . ' from SartajPHP Gate @ ' . date('H:i:s') ); $this->jsServer->addJsonFront($this->frtPanel, 'sphpPanel'); $this->jsServer->addJsonHtmlBlock('sphpStatus', 'Panel Front loaded'); $this->jsServer->addJsonReturnBlock(array('ok' => true, 'who' => $who)); } /** addJsonFront — form with fui-* + validation.js hooks */ public function page_event_form($evtp) { $this->frtForm->spnFormResult->setInnerHTML( 'Form Front via addJsonFront @ ' . date('H:i:s') . ' — empty submit should trip validation.js' ); $this->jsServer->addJsonFront($this->frtForm, 'sphpForm'); $this->jsServer->addJsonHtmlBlock('sphpStatus', 'Form Front loaded (validation.js hooks in js block)'); $this->jsServer->addJsonReturnBlock(array('ok' => true, 'front' => 'form')); } /** Save after client validation — server getCheckErr */ public function page_event_save($evtp) { if (!getCheckErr()) { $name = ''; $email = ''; if ($this->frtForm->getComponent('txtName') !== null) { $name = (string) $this->frtForm->txtName->value; } if ($this->frtForm->getComponent('emlEmail') !== null) { $email = (string) $this->frtForm->emlEmail->value; } if ($name === '') { $name = trim((string) $this->client->request('txtName')); } if ($email === '') { $email = trim((string) $this->client->request('emlEmail')); } $msg = 'OK — Name=' . $name . '; Email=' . $email; $this->jsServer->addJsonHtmlBlock('spnFormResult', $msg); $this->jsServer->addJsonHtmlBlock('sphpStatus', 'Save OK (getCheckErr passed)'); $this->jsServer->addJsonReturnBlock(array( 'ok' => true, 'name' => $name, 'email' => $email, )); } else { $msg = 'Validation failed (getCheckErr)'; $this->jsServer->addJsonHtmlBlock('spnFormResult', $msg); $this->jsServer->addJsonHtmlBlock('sphpStatus', $msg); $this->jsServer->addJsonReturnBlock(array('ok' => false, 'error' => $msg)); } } } ``` ## **25.7 FrontFiles** **Main** — `apps/examples/fronts/exreactajax_main.front` (status + holders): ```html <title id="title1" runat="server">ExReactAjax — SartajPHP ↔ React client</title> <h1>ExReactAjax</h1> <p> Test Gate for <code>comp/reactJs/sphp-client.js</code> (load the client from the public site in your SPA). </p> <p>Status slot: <span id="sphpStatus" class="alert alert-secondary">idle</span></p> <div id="sphpPanel"></div> <div id="sphpForm"></div> ``` **Panel** — `apps/examples/fronts/exreactajax_panel.front`: ```html <div class="sphp-panel"> <strong id="spnPanelTitle" runat="server">Panel</strong> <p id="spnPanelBody" runat="server" class="mb-0">…</p> </div> ``` **Form** — `apps/examples/fronts/exreactajax_form.front` (fui validation + hook for React to POST after client checks pass): ```html <span id="spnFormResult" runat="server" class="alert alert-info d-block mb-2"> Fill the form (client validation.js + server getCheckErr) </span> <form id="formReact" runat="server" method="post" action="##{getEventUrl('save','','exreactajax')}#" fun-setOnValidation="(typeof window.onSphpSpaFormSave==='function'?window.onSphpSpaFormSave():false)"> <div class="mb-2"> <label for="txtName">Name</label> <input id="txtName" runat="server" type="text" class="form-control" fui-setForm="formReact" fun-setMsgName="Name" fui-setRequired="" fui-setMinLen="3" placeholder="min 3 chars" /> </div> <div class="mb-2"> <label for="emlEmail">Email</label> <input id="emlEmail" runat="server" type="email" class="form-control" fui-setForm="formReact" fun-setMsgName="Email" fui-setRequired="" fui-setEmail="" placeholder="you@example.com" /> </div> <button type="submit" class="btn btn-primary">Save (validate)</button> </form> ``` ## **25.8 React: Load Form + validation.js** HTMLForm / fui fields emit submit hooks that call `checkTextEmpty`, `checkemails`, etc. Those live in the same assets classic pages load: 1. jQuery 2. `jslib.js` (`get_browser`, `isset`, …) 3. `validation.js` With `baseUrl` set to your SartajPhp app, `ensureFormLibs()` loads them from that origin: ```js await sphp.ensureFormLibs() sphp.getAjaxReturn('exreactajax-form.html', {}, true, (retobj) => { console.log(retobj) }) ``` After validation passes, `fun-setOnValidation` calls a global you define so the SPA does not do a full page post: ```js window.onSphpSpaFormSave = function () { const form = document.getElementById('formReact') if (!form) { return false } const data = Object.fromEntries(new FormData(form).entries()) sphp.getAjaxReturn('exreactajax-save.html', data, true, (retobj) => { console.log('save', retobj) }) return false // stop native submit; client checks already passed } ``` **Important:** use a **plain** `<div id="sphpForm" />` for injected forms. `SphpSlot` re-renders with React and **wipes jQuery submit handlers** attached by the Front’s `sphpajready1` block. Status text can still use `SphpSlot`. ```jsx <SphpSlot id="sphpStatus" fallback="idle" /> <button type="button" onClick={loadForm}>Load form Front</button> <div id="sphpForm" className="form-slot" /> ``` ## **25.9 Optional React Helpers (`sphp-react.jsx`)** ```jsx import { useEffect, useState } from 'react' import sphp from './sphp-client.js' export function useSphpHtml(id, initial = '') { const [html, setHtml] = useState(() => { const cur = sphp.getHtml(id) return cur !== undefined ? cur : initial }) useEffect(() => sphp.subscribeHtml(id, setHtml), [id]) return html } export function SphpSlot({ id, className, fallback = '' }) { const html = useSphpHtml(id, fallback) return ( <div id={id} className={className} dangerouslySetInnerHTML={{ __html: html || '' }} /> ) } ``` ## **25.10 Client API Checklist** | Method | Purpose | |--------|---------| | `sphp.configure({ baseUrl, credentials, debug })` | Your SartajPhp app origin + cookies | | `sphp.sendAjax(url, data)` | Fire-and-forget jsServer blocks | | `sphp.getAjaxReturn(url, data, raw, cb)` | Blocks + `retobj` callback | | `sphp.callNativeGate(gate, evt, evtp, data)` | WebSocket NativeGate (set `sphp.frontobj.websockethost`) | | `sphp.ensureFormLibs()` | jQuery + jslib + validation.js from `baseUrl` | | `sphp.subscribeHtml(id, fn)` / `sphp.getHtml(id)` | React bindings for HTML blocks | jsServer block order applied by the client (same idea as `ajax.js`): `jss` → optional `jsfl` / `fileList` scripts → `html` → `js` → `jsp` → `jsf` → `sphpajready1`. ## **25.11 Checklist — Ship Your Own Feature** 1. Keep/update `comp/reactJs/` on this docs site (shared client), or ship the same folder in your own SartajPhp project. 2. Add or reuse a Gate with `page_event_*` + `jsServer` on **your** app. 3. In the SPA, import the client from `comp/reactJs/`, and set `baseUrl` to **your** SartajPhp website origin. 4. Call `sendAjax` / `getAjaxReturn` with relative event paths (`mygate-myevent.html`). 5. For `addJsonFront` forms: `ensureFormLibs()`, plain holder div, optional `onSphpSpaFormSave` + `getCheckErr` on save. ## **25.12 Maintainer note — local testing only** Local Apache + Vite proxy is **only** for people developing this repository on their machine. Public readers should ignore this section and use §25.4–25.5. When testing a local clone before deploy: proxy a Vite prefix to your local project folder that contains `start.php`, and temporarily point `baseUrl` / aliases at that local app. Do not publish those local host or folder names in docs or sample apps meant for the public site. ## **25.13 Next Steps** - Chapter 26 — same Gate calls from a **Vue** Vite app (`comp/vueJs/`) - Re-read Chapter 13 for `addJsonFront` / `addJsonReturnBlock` patterns - Use `callNativeGate` with Chapter 22 (NativeGate / SphpServer) - Prefer Gate + jsServer over re-implementing PHP logic inside React --- **Summary:** Share `comp/reactJs/` from this docs site (or your own app). Set `baseUrl` to **any** SartajPhp website that hosts your Gates. Keep the same `sendAjax` / `getAjaxReturn` / `callNativeGate` names. React owns UI; Gates own events and jsServer. Local servers are for maintainers only.