PHP code example of zotenme / hyperf-ajax

1. Go to this page and download the library: Download zotenme/hyperf-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/ */

    

zotenme / hyperf-ajax example snippets




declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Zotenme\HyperfAjax\Controller\HyperfAjaxController;

class ProfileController extends HyperfAjaxController
{
    public function index(RequestInterface $request, ResponseInterface $response)
    {
        return $this->ajaxPage(
            $request,
            $response,
            fn () => view('profile.index'),
            'index'
        );
    }

    public function onSave()
    {
        return $this
            ->ajax()
            ->update(['#message' => 'Saved'])
            ->browserEvent('profile:saved', ['ok' => true]);
    }
}

use Hyperf\HttpServer\Router\Router;

Router::addRoute(['GET', 'POST'], '/profile', [ProfileController::class, 'index']);



declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Zotenme\HyperfAjax\Controller\HyperfAjaxController;

class HyperfAjaxTestController extends HyperfAjaxController
{
    public function index(RequestInterface $request, ResponseInterface $response)
    {
        return $this->ajaxPage($request, $response, function () use ($response) {
            $html = <<<'HTML'
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <script src="/vendor/hyperfajax/framework-bundle.min.js"></script>
    <style>
        [data-validate-for],
        [data-validate-error] { display: none; color: #b00020; margin-top: 4px; }
        [data-validate-for].jax-visible,
        [data-validate-error].jax-visible { display: block; }
    </style>
</head>
<body>
    <form data-request="onPing" data-request-validate>
        <input name="name" placeholder="Name">
        <div data-validate-for="name"></div>

        <button type="submit">Ping</button>
    </form>

    <div id="message"></div>
</body>
</html>
HTML;

            return $response->html($html);
        }, 'index');
    }

    public function onPing()
    {
        $name = trim((string) $this->ajaxPost('name', ''));

        if ($name === '') {
            return $this
                ->ajax()
                ->invalidField('name', 'Name is 

use App\Controller\HyperfAjaxTestController;
use Hyperf\HttpServer\Router\Router;

Router::addRoute(['GET', 'POST'], '/hyperfajax-test', [HyperfAjaxTestController::class, 'index']);

public function onSave()
{
    $data = $this->ajaxAll();
    $phone = $this->ajaxPost('phone');

    if (! $phone) {
        return $this->ajax()->invalidField('phone', 'Phone is 

use App\Ajax\CustomHandlerInvoker;
use Zotenme\HyperfAjax\Contracts\AjaxHandlerInvokerInterface;

return [
    AjaxHandlerInvokerInterface::class => CustomHandlerInvoker::class,
];

final class CustomHandlerInvoker implements AjaxHandlerInvokerInterface
{
    public function invoke(callable $handler, array $parameters = []): mixed
    {
        return $handler(...$parameters);
    }
}

use Zotenme\HyperfAjax\Exception\ValidationException;

public function onSave()
{
    $validator = $this->validationFactory->make(
        $this->ajaxPost(),
        [
            'email' => [' ValidationException::fromValidator($validator);
    }

    return $this->ajax()->update([
        '#message' => 'Saved',
    ]);
}

throw new ValidationException([
    'email' => ['Email is 

use Zotenme\HyperfAjax\Controller\HyperfAjaxController;

class ProfileController extends HyperfAjaxController
{
    public array $components = [
        ProfileForm::class,
    ];
}

use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ContainerInterface;
use Zotenme\HyperfAjax\Concerns\InteractsWithAjax;
use Zotenme\HyperfAjax\Contracts\AjaxControllerInterface;

class ProfileController implements AjaxControllerInterface
{
    use InteractsWithAjax;

    protected function getAjaxContainer(): ContainerInterface
    {
        return ApplicationContext::getContainer();
    }
}

use Zotenme\HyperfAjax\Concerns\ViewComponent;
use Zotenme\HyperfAjax\Contracts\ViewComponentInterface;

class ProfileForm implements ViewComponentInterface
{
    use ViewComponent;

    public function onSave()
    {
        return $this->ajax()->update(['#message' => 'Saved from component']);
    }
}

public function onSave(): AjaxResponse
{
    return $this->ajax()->flash('success', 'Profile saved');
}

return $this->ajax()->partial(
    'profile/message',
    '<div data-ajax-partial="profile/message">Updated</div>'
);

use App\Ajax\PlainPhpPartialRenderer;
use Zotenme\HyperfAjax\Contracts\PartialRendererInterface;

return [
    PartialRendererInterface::class => PlainPhpPartialRenderer::class,
];

use Zotenme\HyperfAjax\AjaxRequest;
use Zotenme\HyperfAjax\Contracts\PartialRendererInterface;

final class PlainPhpPartialRenderer implements PartialRendererInterface
{
    public function render(
        string $partial,
        object $controller,
        AjaxRequest $request,
        array $data = []
    ): string {
        return '<div data-ajax-partial="' . htmlspecialchars($partial) . '">'
            . htmlspecialchars((string) ($data['message'] ?? ''))
            . '</div>';
    }
}

public function onSave(): AjaxResponse
{
    $this->withAjaxPartialData(['message' => 'Profile saved']);

    return $this->ajax()->data(['saved' => true]);
}

use Hyperf\View\RenderInterface;

final class HyperfViewPartialRenderer implements PartialRendererInterface
{
    public function __construct(private readonly RenderInterface $view) {}

    public function render(
        string $partial,
        object $controller,
        AjaxRequest $request,
        array $data = []
    ): string {
        $view = match ($partial) {
            'profile/message' => 'partials.profile-message',
            default => throw new InvalidArgumentException("Unknown partial [{$partial}]."),
        };

        return $this->view->getContents($view, $data);
    }
}