PHP code example of pinkcrab / ajax

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

    

pinkcrab / ajax example snippets


// file:plugin.php

// Boot the app as normal, including the module.
$app = ( new App_Factory )      
    ->default_setup()
    ->module( \PinkCrab\Ajax\Module\Ajax::class )
    ->boot();

use PinkCrab\Ajax\Ajax;
use PinkCrab\Ajax\Ajax_Helper;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use PinkCrab\Ajax\Dispatcher\Response_Factory;

class My_Ajax extends Ajax {

    /**
     * Define the action to call.
     * @var string
     */
    protected $action = 'my_ajax_action';

    /**
     * The ajax calls nonce handle.
     * @var string
     */
    protected $nonce_handle = 'my_ajax_nonce';

    /** 
     * Some service which handles the logic of the call.
     * @var Some_Service 
     */
    protected $my_service;

    /**
     * Constructs the object
     * My_Service will be injected when this is created by the DI Container
     */
    public function __construct( Some_Service $my_service ) {
        $this->my_service = $my_service;
    }

    /**
     * The callback
     *
     * @param \Psr\Http\Message\ServerRequestInterface $request
     * @param \PinkCrab\Ajax\Dispatcher\Response_Factory $response_factory
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function callback(
        ServerRequestInterface $request,
        Response_Factory $response_factory
    ): ResponseInterface {
        
        // Extract the args from the request, you can also do this manually
        $args = Ajax_Helper::extract_server_request_args( $request );

        // Do something with the request args, ideally in a service class
        $data_to_return = array_key_exists('foo', $args)
            ? $this->my_service->do_something($args['foo'])
            : 'Foo not found!';
        
        // Return with a valid PSR Response. 
        return $response_factory->success( $data_to_return );
    }
}


// file:registration.php

return [
    ....
    My_Ajax_Call::class,
    ....
];