Functions

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

pphp.fetch Function

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 sends a request to the server, specifying a callback function and additional data. It utilizes the pphp.fetch function internally to perform the HTTP request. By default, pphp.fetchFunction uses the current page URL (window.location.href) and sends the data as a JSON string in the request body.

public async fetchFunction<T = any>(
    functionName: string,
    data: Record<string, any> = {},
    abortPrevious: boolean = false
  ): Promise<T | string> {}

Example Usage

<?php

function testFunction($data)
{
    return $data;
}

?>

<button onclick="callTestFunction">Abort Request</button>

<script>
    async function callTestFunction() {
        // Sending a request to the server with the function name 'testFunction' and data { name: 'John Doe' }
        const responseData = await pphp.fetchFunction('testFunction', { name: 'John Doe' });
        console.log(responseData);
    }
</script>
<?php

function uploadFile($data)
{
    sleep(5);
    return $data;
}

?>

<div class="bg-gray-100 p-10 grid place-items-center h-screen">
    <div class="max-w-xl mx-auto bg-white shadow-md rounded-xl p-6 space-y-6">
        <h1 class="text-2xl font-bold text-gray-800">📤 Upload a File</h1>

        <form onsubmit="submitForm" class="space-y-4">
            <input type="test" name="name" placeholder="Name" class="block w-full text-sm text-gray-700 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 p-2" />

            <input type="file" name="file" class="block w-full text-sm text-gray-700 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 p-2" />

            <div class="flex space-x-4">
                <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition">
                    Upload
                </button>
                <button type="button" id="cancel-btn" onclick="cancelUpload" class="bg-red-500 text-white px-4 py-2 rounded-md hover:bg-red-600 transition">
                    Cancel
                </button>
            </div>
        </form>

        <div id="status" class="text-sm text-gray-700 font-medium mt-4"></div>
    </div>
</div>

<script>
    async function submitForm(form) {
        console.log("🚀 ~ submitForm ~ form:", form);

        const responseData = await pphp.fetchFunction("uploadFile", form.data, true);
        console.log("🚀 ~ submitForm ~ responseData:", responseData)
    }

    function cancelUpload() {
        console.log("🚀 ~ cancelUpload ~ Cancel Upload")
        pphp.abortActiveRequest();
    }
</script>

pphp.sync Function

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>