Documentation

On this page

Download full book (text)

# **Chapter 13: AJAX and jsServer — Updating the Page Without Reloads** > **Prerequisites:** Chapters 1-5 (Gates, Page Events, FrontFiles) > **Try it:** Tested code from gate `ex07ajax` > (`apps/examples/Ex07ajax.gate.php` + `apps/examples/fronts/ex07ajax_main.front`). > Open `http://localhost/SartajPhpDoc/ex07ajax.html`. --- ## **13.1 The SartajPhp AJAX Model** In a classic PHP app, AJAX means writing `fetch()` calls, JSON parsing, and DOM updates by hand. In SartajPhp the **Gate answers AJAX with instructions**, not data: the Gate fills a `jsServer` object ("JS Server") with blocks — replace this HTML, run this JS, swap this FrontFile, return this value — and the framework ships them to the browser, which executes them in order. ```mermaid sequenceDiagram participant B as Browser participant G as Gate (page_event_*) participant J as jsServer B->>G: sendAjax(url, data) G->>J: addJsonHtmlBlock / addJsonFront / callJsFunction J-->>B: JSON blocks B->>B: apply HTML, run JS, swap Front ``` Two browser helpers, two response styles: | Browser call | Gate response | Use when | |--------------|---------------|----------| | `sendAjax(url, data)` | jsServer blocks (fire-and-forget) | Server updates the page itself | | `getAjaxReturn(url, data, raw, cb)` | `addJsonReturnBlock($value)` + callback | Browser JS needs the value | ## **13.2 sendAjax → jsServer Blocks** Browser side (`ex07ajax_main.front`): ```html <button type="button" class="btn btn-sm btn-primary" onclick="doPing();">Ping (sendAjax)</button> <p>Callback from server: <span id="spnPingCb">—</span></p> <script type="text/javascript"> function doPing(){ sendAjax("##{getEventUrl('ping')}#", { txtname: $("#txtname").val() }); } function onAjaxPing(msg){ $("#spnPingCb").text(String(msg)); } </script> ``` Gate side (`apps/examples/Ex07ajax.gate.php`) — note there is **no** `setFrontFile()`; the jsServer blocks are the whole response: ```php <?php // apps/examples/Ex07ajax.gate.php /** sendAjax / button — update HTML + run JS (no callback). URL: ex07ajax-ping.html */ public function page_event_ping($evtp) { $name = trim((string) $this->client->request('txtname')); if ($name === '') { $name = 'guest'; } $msg = 'Pong ' . $name . ' @ ' . date('H:i:s'); $this->jsServer->addJsonHtmlBlock('spnStatus', $msg); $this->jsServer->addJsonJsBlock("$('#spnStatus').addClass('text-success');"); $this->jsServer->callJsFunction('onAjaxPing', $msg); } ``` The three jsServer calls used here: | Method | Effect in browser | |--------|-------------------| | `addJsonHtmlBlock($id, $html)` | Replace innerHTML of element `$id` | | `addJsonJsBlock($js)` | Run raw JS (jQuery is available) | | `callJsFunction($name, $arg)` | Call a global JS function with data | `$this->client->request('txtname')` reads the POST field the browser sent — same API as reading a form on a normal submit. ## **13.3 getAjaxReturn → addJsonReturnBlock (JS Callback)** When browser code needs the server value (not just updated HTML), the Gate fills a **return block** and the browser callback receives it: ```php <?php /** getAjaxReturn — value for browser callback. URL: ex07ajax-echo.html */ public function page_event_echo($evtp) { $text = trim((string) $this->client->request('txt')); if ($text === '') { $text = (string) $evtp; } if ($text === '') { $text = '(empty)'; } $this->jsServer->addJsonHtmlBlock('spnStatus', 'Echoed via jsServer'); $this->jsServer->addJsonReturnBlock(array( 'ok' => true, 'echo' => $text, 'at' => date('c'), )); } ``` ```html <script type="text/javascript"> function doEcho(){ getAjaxReturn("##{getEventUrl('echo')}#", { txt: $("#txtecho").val() }, false, function(ret){ $("#preEcho").text(typeof ret === "string" ? ret : JSON.stringify(ret, null, 2)); }); } </script> ``` `addJsonReturnBlock` accepts a string or an array (arrives as a JS object). You can combine it with HTML blocks — both are applied, then the callback runs. ## **13.4 Form AJAX: `fun-setAJAX=""`** A form with `fun-setAJAX=""` posts via AJAX to its `action` URL — no page reload, no hand-written JS: ```html <form id="frmCalc" runat="server" fun-setAJAX="" action="##{getEventUrl('calc')}#"> <input id="numa" type="number" runat="server" value="7" /> <select id="sltop" runat="server"> <option value="+" selected>+</option> <option value="-">-</option> </select> <input id="numb" type="number" runat="server" value="3" /> <button type="submit">Calculate</button> </form> <p>Result: <strong id="spnResult">—</strong></p> ``` The Gate handler is an ordinary Page Event — it reads components/fields and answers with jsServer blocks: ```php <?php /** Form with fun-setAJAX="" — posts fields without full page reload. */ public function page_event_calc($evtp) { $a = (int) $this->client->request('numa'); $b = (int) $this->client->request('numb'); $op = (string) $this->client->request('sltop'); // live* fields (Section 13.6) override when present if ($this->client->request('liveA') !== null && $this->client->request('liveA') !== '') { $a = (int) $this->client->request('liveA'); } if ($this->client->request('liveB') !== null && $this->client->request('liveB') !== '') { $b = (int) $this->client->request('liveB'); } if ($this->client->request('liveOp') !== null && $this->client->request('liveOp') !== '') { $op = (string) $this->client->request('liveOp'); } $res = ($op === '-') ? $a - $b : $a + $b; if ($op !== '-') { $op = '+'; } $this->jsServer->addJsonHtmlBlock('spnResult', (string) $res); $this->jsServer->addJsonHtmlBlock('spnStatus', $a . ' ' . $op . ' ' . $b . ' = ' . $res); } ``` ## **13.5 addJsonFront — Swap a FrontFile Into a Holder (SPA Panels)** `addJsonFront($frontFile, $holderId)` renders a **whole FrontFile** on the server and replaces the innerHTML of `$holderId` in the browser. This is how SartajPhp builds SPA-style panels — the injected Front carries its own components, events, and JS: ```php <?php /** Swap a FrontFile fragment into #panelHolder. URL: ex07ajax-panel-info.html */ public function page_event_panel($evtp) { $key = strtolower(preg_replace('/[^a-z]/', '', (string) $evtp)); if ($key !== 'help') { $key = 'info'; } $this->frtPanel->spnPanelTitle->setInnerHTML($key === 'help' ? 'Help panel' : 'Info panel'); $this->frtPanel->spnPanelBody->setInnerHTML( $key === 'help' ? 'Use sendAjax for fire-and-forget jsServer blocks; getAjaxReturn when you need a JS callback.' : 'Loaded by addJsonFront at ' . date('H:i:s') ); $this->jsServer->addJsonFront($this->frtPanel, 'panelHolder'); $this->jsServer->addJsonHtmlBlock('spnStatus', 'Panel: ' . $key); } ``` ```html <button onclick="sendAjax('##{getEventUrl('panel','info')}#', {});">Load info</button> <button onclick="sendAjax('##{getEventUrl('panel','help')}#', {});">Load help</button> <div id="panelHolder" class="border rounded p-2">(panel)</div> ``` The same mechanism powers the AJAX edit forms in Chapters 11 and 17 (`rowclick` → `addJsonFront($genFormFront, 'edtHolder')`). ## **13.6 Component AJAX: `fun-submitAJAX` (Zero JS)** A single component can post itself on any DOM event — no `<script>` at all. Pipe syntax: ``` fun-submitAJAX="event,|url,|extraId1,extraId2" ``` ```html <input id="liveA" runat="server" type="number" value="4" fun-submitAJAX="keyup,|##{getEventUrl('calc')}#,|liveB,liveOp" /> <select id="liveOp" runat="server" fun-submitAJAX="change,|##{getEventUrl('calc')}#,|liveA,liveB"> ``` Every keyup in `liveA` posts `liveA` **plus the listed extra ids** to `page_event_calc` — a live calculator with no handwritten JS. **Default URL rule (tested):** with an empty URL part, `fun-submitAJAX="keyup"` posts to `page_event_{componentId}_{event}` — here `txtLive` keyup lands in: ```php <?php /** fun-submitAJAX default → page_event_{compId}_{domEvent} */ public function page_event_txtLive_keyup($evtp) { $v = ''; if ($this->frtMain->getComponent('txtLive') !== null) { $v = (string) $this->frtMain->txtLive->value; } if ($v === '') { $v = (string) $this->client->request('txtLive'); } $this->jsServer->addJsonHtmlBlock('spnLive', 'Live: ' . $v); } ``` The WebSocket twin `fun-submitWS="click,|host,|extraIds,|nativeGate,|evt,|evtp"` sends the same payload over a NativeGate socket (Chapter 22). ## **13.7 jsServer Method Summary** | Method | Payload | |--------|---------| | `addJsonHtmlBlock($id, $html)` | Replace innerHTML of `$id` | | `addJsonJsBlock($js)` | Run JS in page context | | `callJsFunction($fn, $arg)` | Call global JS function | | `addJsonFront($front, $holderId)` | Render FrontFile into holder | | `addJsonComp($comp, $holderId)` | Render one component into holder | | `addJsonBlock($type, $id, $html)` | Low-level block (used for `pagebar`) | | `addJsonReturnBlock($value)` | Value for `getAjaxReturn` callback | Pagination AJAX refresh uses `addJsonComp` + `addJsonBlock` (see Chapter 17): ```php public function page_event_showall_show($evtp) { $showall = $this->showallFront->getComponent('showall'); $this->jsServer->addJsonComp($showall, 'showall'); $this->jsServer->addJsonBlock('html', 'pagebar', $showall->getPageBar()); } ``` ## **13.8 Rules of Thumb** 1. **An AJAX Page Event usually does NOT call `setFrontFile()`** — the jsServer blocks are the response. (Full-page events do the opposite.) 2. **Read input with `$this->client->request('name')`** — works for `sendAjax` payloads, AJAX forms, and normal POSTs alike. 3. **Prefer `fun-submitAJAX` / `fun-setAJAX`** over handwritten `sendAjax` when the trigger is a component; use `sendAjax` from custom JS when the trigger is arbitrary logic. 4. **`addJsonFront` for panels/editors, `addJsonHtmlBlock` for small text swaps** — don't ship a whole Front to change one label. 5. **AJAX events are normal events** — authentication, permissions, and `getCheckErr()` checks apply exactly as on full pages. ## **13.9 Verify It Yourself** Against `http://localhost/SartajPhpDoc/`: 1. Open `ex07ajax.html` 2. Click **Ping** → status shows `Pong Ada @ HH:MM:SS`, callback line updates 3. Click **Echo** → JSON `{ok, echo, at}` appears in the `<pre>` 4. Change A/B/Op in form 3 → result updates without reload 5. Click **Load help** → panel swaps via `addJsonFront` 6. Type in the live inputs → `page_event_calc` runs per keyup 7. Type in `txtLive` → default-URL event `page_event_txtLive_keyup` fires --- **Next:** [Chapter 14 — Permissions and Authentication](chapter14.md)