Functions

Special functions that can be called to perform a specific task.

pphp.fetch

The pphp.fetch function is an asynchronous utility for making HTTP requests. It automatically adds the header X-Requested-With: XMLHttpRequest to distinguish these requests as XMLHttpRequest calls, accept a URL and optional options, and return the response as text.

public async fetch(
    url: string,
    options?: RequestInit,
    abortPrevious: boolean = false
  ): Promise<Response> {}

Example Usage

<script>
    const fetchData = async () => {
        // Sending a GET request to retrieve data from '/api/data'
        const response = await pphp.fetch('/api/data', {
            method: 'GET',
        });
        // Logging the response text to the console
        console.log(response);
    };

    fetchData();
</script>

Aborting Active Request

<button onclick="pphp.abortActiveRequest()">Abort Request</button>
<script>
    // Initiating a GET request to '/api/data' with abortPrevious set to true.
    // This ensures any ongoing request is canceled before starting a new one.
    const responseData = await pphp.fetch('/api/data', {
        method: 'GET',
    }, true); // abortPrevious = true allows you to abort the ongoing request using the button above.
</script>

pphp.fetchFunction

The pphp.fetchFunction helper sends a request to the current page URL (window.location.href) to invoke a server callback with data. Internally it encrypts the callback name, auto-detects files to send FormData, and returns either parsed JSON or raw text.

  • Encrypts the callback name before sending.
  • Auto-uses FormData if any value in data is a File or FileList; otherwise sends JSON.
  • Supports aborting the previous in-flight request via the abortPrevious boolean.
  • Returns parsed JSON (T) when possible; falls back to string.
  • When aborted intentionally, returns { cancelled: true }.
public async fetchFunction<T = any>(
  functionName: string,
  data: Record<string, any> = {},
  abortPrevious: boolean = false
): Promise<T | string> {}

Parameters

Param Type Default Description
functionName string Server callback name. It’s encrypted internally before sending.
data Record<string, any> {} Payload for the callback. If it contains files (File/FileList), a FormData request is automatically performed; otherwise JSON is used.
abortPrevious boolean false If true, aborts any active request before starting this one. You can also abort manually with pphp.abortActiveRequest().

Basic Example

<?php
function hello($data) {
  return ['message' => 'Hello ' . ($data->name ?? 'World') . '!'];
}
?>

<button class="btn btn-primary" onclick="callHello">Say Hello</button>

<script>
async function callHello() {
  const res = await pphp.fetchFunction('hello', { name: 'Prisma PHP' });
  console.log(res); // { message: "Hello Prisma PHP!" }
}
</script>

Abort the previous request

<button class="btn btn-secondary" onclick="saveProfile">Save</button>
<button class="btn btn-ghost" type="button" onclick="pphp.abortActiveRequest()">Cancel active</button>

<script>
async function saveProfile() {
  // If a previous request is in-flight, it will be aborted first
  const result = await pphp.fetchFunction('saveUser', { id: 1, name: 'Ada' }, true);
  if (result && result.cancelled) {
    console.log('Request was cancelled');
    return;
  }
  console.log(result);
}
</script>

File uploads (auto-FormData)

<form id="avatar-form" onsubmit="sendAvatar(this); return false;" class="max-w-md space-y-3">
  <input class="file-input file-input-bordered w-full" type="file" name="avatar" />
  <button class="btn btn-primary" type="submit">Upload</button>
</form>

<script>
async function sendAvatar(form) {
  const fileInput = form.querySelector('input[name="avatar"]');
  const data = { avatar: fileInput.files }; // FileList supported

  const res = await pphp.fetchFunction('uploadAvatar', data, true);

  if (res && res.cancelled) {
    console.log('Upload cancelled');
    return;
  }

  console.log('Upload response:', res);
}
</script>

Return value

  • T — JSON parsed result (when the server returns JSON).
  • string — raw text when the response is not JSON.
  • { cancelled: true } — when the request was intentionally aborted.

pphp.sync

The pphp.sync function synchronizes elements marked with pp-sync attributes. It retrieves the updated content from the server and applies it to the corresponding elements in the DOM. This function is particularly useful for keeping the client-side UI synchronized with server-side changes.

There are three conditions to be aware of when using this function:

  • By default, the pp-sync="true" attribute updates all elements when the pphp.sync function is called without any arguments.
  • To update a specific element, such as one with the ID users-table, use the pp-sync="users-table" attribute and call the pphp.sync function with the argument 'users-table'.
  • To update multiple specific elements, such as those with the IDs users-table and notifications, use the pp-sync attribute for each element and call the pphp.sync function with the arguments 'users-table' and 'notifications'.
async function pphp.sync(...prefixes: string[]) {}

Example Usage

<?php

use Lib\StateManager;

$userName = StateManager::getState('userName', 'Guest');

function testSync()
{
    StateManager::setState('userName', 'Admin');
    return [
        'success' => 'Hello, World!'
    ];
}

?>

<button onclick="testSync" pp-after-request="testSyncResponse">Click Me!</button>

<p pp-sync="true">Hello, <?= $userName ?></p>
<p pp-sync="userName"><?= $userName ?></p>
<p pp-sync="userName2"><?= $userName ?></p>

<script>
    async function testSyncResponse(response) {
        console.log(response);
        // await pphp.sync();
        await pphp.sync('userName');
        // await pphp.sync('userName', 'userName2');
    }
</script>

Synchronizing elements with the prefixes 'userName' and 'userName2' ensures that the corresponding sections of the UI remain up-to-date with changes made on the server.

Note: The pphp.sync attribute re-renders script tags within the content being replaced. However, if you are using MainLayout and injecting your script tags, they will not be re-rendered. The primary purpose of pphp.sync is to update the content of the specified elements or HTML. Any script tags within the updated content will be re-rendered and executed.

pphp.fetchAndUpdateBodyContent

The pphp.fetchAndUpdateBodyContent function fetches the content of the specified URL and updates the body of the current page with the retrieved content. This function is useful for loading new content without refreshing the entire page.

async function pphp.fetchAndUpdateBodyContent() {}

Example Usage

<button onclick="pphp.fetchAndUpdateBodyContent()">Load New Page</button>
<input
    class="sm:w-1/4 w-full sm:order-1 order-2"
    type="search"
    name="search"
    oninput="pphp.fetchAndUpdateBodyContent()"
    pp-debounce="400"
    placeholder="Search..."
    pp-append-params="true"
    pp-append-params-sync="true"
    pp-autofocus="{'end': true}" />

Note: The pphp.fetchAndUpdateBodyContent function fetches the content of the current page URL by default and replaces the body content with the new content. This means that any script tags within the body content will be re-rendered and executed. Additionally, script tags injected using the MainLayout's addFooterScript method will also be re-rendered and executed. In simple terms, this function updates the body content with the fetched content.

pphp.redirect

The pphp.redirect function allows you to programmatically redirect users to a specified URL. By passing a URL string as an argument, this function navigates the browser to the desired location. It is particularly useful for scenarios such as redirecting users after form submissions, button clicks, or other actions where using a traditional anchor tag is not ideal.

public async redirect(url: string): Promise<void> {}

Example Usage

<button onclick="goToDashboard">Go to dashboard</button>
<script>
    async function goToDashboard() {
        await pphp.redirect('/dashboard');
    }
</script>