Ajax (Pro)

The Pro edition has the Custom_Data feature for Views and Cards, which allows for highly customizing the components. Besides passing extra arguments mentioned in the linked guides, you can also add Ajax to your components.

This feature is built on top of the built-in WordPress Ajax feature and allows you to easily master Ajax functionality inside Views and Cards.

To use it, you just need to override the get_ajax_response() method inside the Custom_Data instance. The return should be an array, which will be passed as JSON to the client. Then, on the client, you need to request the admin-ajax.php file with the advanced_views action and pass the View or Card ID.

Inside the callback, you can use any WordPress functions. Furthermore, you can employ PHP-DI to get direct access to your theme classes.

Example of usage

script.js

async function makeAjax() {
    let response = await fetch('/wp-admin/admin-ajax.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            'action': 'advanced_views',
            // todo put your View ID or comment if it's a Card 
            '_viewId': '6630e2da1953e', // you can learn ID from the shortcode
            // todo put your Card ID or comment if it's a View 
            '_cardId': '6630e2da1953e', // you can learn ID from the shortcode
            // todo your args here
            'myArg': 'myvalue',
        }).toString(),
    });

    let responseText = await response.text();
    let json = {};

    try {
        json = JSON.parse(responseText);
    } catch (e) {
        console.log("Error parsing JSON", responseText);
        return;
    }

    console.log('ajax complete', json);
}

view.php

<?php

declare( strict_types=1 );

use Org\Wplake\Advanced_Views\Pro\Bridge\Views\Custom_View_Data;

return new class extends Custom_View_Data {
	public function get_ajax_response(): array {
		$myArg = sanitize_text_field( $_POST['myArg'] ?? '' );

		// todo your logic here
		// additionally, you can use $this->get_container()
		// to get PHP-DI instance and access to any of your theme classes

		return [
			'my_response' => 'Thank you for the feedback!',
		];
	}
};

card.php

<?php

declare( strict_types=1 );

use Org\Wplake\Advanced_Views\Pro\Bridge\Cards\Custom_Card_Data;

return new class extends Custom_Card_Data {
	public function get_ajax_response(): array {
		$myArg = sanitize_text_field( $_POST['myArg'] ?? '' );

		// todo your logic here
		// additionally, you can use $this->get_container()
		// to get PHP-DI instance and access to any of your theme classes

		return [
			'my_response' => 'Thank you for the feedback!',
		];
	}
};

Last updated