PHP code example of pollora / ajax

1. Go to this page and download the library: Download pollora/ajax library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pollora / ajax example snippets


use Pollora\Ajax\Ajax;

// Logged-in users only (default, wp_ajax_my_action)
Ajax::listen('my_action', function (): void {
    wp_send_json_success(['message' => 'It works!']);
});

// Everyone: wp_ajax_* and wp_ajax_nopriv_* (explicit opt-in)
Ajax::listen('public_action', fn () => wp_send_json_success())->forAllUsers();

// Guests only (wp_ajax_nopriv_*)
Ajax::listen('guest_action', fn () => wp_send_json_success())->forGuestUsers();

use Pollora\Ajax\Domain\Model\AjaxAccess;
use Pollora\Attributes\Ajax;

class NewsletterHandler
{
    #[Ajax('subscribe')]
    public function subscribe(): void
    {
        wp_send_json_success(['message' => 'Subscribed!']);
    }

    #[Ajax('load_more', access: AjaxAccess::ALL)]
    public function loadMore(): void
    {
        wp_send_json_success([/* ... */]);
    }
}

// The page creates the nonce and sends it in the `_ajax_nonce` field (or `_wpnonce`).
$nonce = Ajax::nonce('save_note');

// The action refuses a request without a valid one: 403, and the callback does not run.
Ajax::listen('save_note', $callback)->, $callback)->forGuestUsers()->withoutNonce();

add_filter('pollora/ajax/nonce_by_default', '__return_true');

// The action refuses a logged-in user who lacks the capability: 403, and the callback does not run.
Ajax::listen('save_note', $callback)->