Custom Ajax & Rest API (Pro)

About the feature

The Pro edition has the Custom_Data feature for Views and Cards, allowing for extensive customization of components. In addition to passing extra arguments as mentioned in the linked guides, you can also add AJAX and REST API listeners to your components.

This feature builds on top of the built-in WordPress Ajax and REST API, enabling you to create components that can send data and update themselves in the background without refreshing the page.

To use this feature, override the get_ajax_response() or get_rest_api_response() method inside the Custom_Data instance. The return value should be an array, which will be passed as JSON to the client.

On the client side, you need to send requests to the admin-ajax.php file for AJAX scenarios, or to /wp-json for REST API scenarios.

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

Tip: Not sure about the difference between AJAX and REST API? If you don’t have specific limitations, we recommend using the REST API. It is much faster compared to the traditional admin-ajax.php as it skips loading unnecessary WordPress parts (while still making all necessary WordPress functions available, as it is called on the init action).

Example of Rest API usage

script.js

async function makeRequest(postId, value) {
// 1. todo use '/wp-json/advanced_views/v1/view/' for Views, 
// and put your View ID at the end

// 2. todo use '/wp-json/advanced_views/v1/card/' for Cards, 
// and put your Card ID at the end

    await fetch('/wp-json/advanced_views/v1/{view|card}/{6630e2da1953e}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
        // todo your arguments here
           'postId': postId,
            'value': 'value,
        }),
    }).then(response => response.json())
        .then((response) => {
            // todo process response, the variable already contains the parsed object 
            console.log('Request complete', response);
        })
        .catch(error => () => {
            console.error('Request error:', error)
        });
}

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 {

	/**
	 * @return array<string,mixed>
	 */
	public function get_rest_api_response( WP_REST_Request $request ): array {
		$request_arguments = $request->get_json_params();
		// todo process the request, based on the query arguments available inside the $input array

		// todo you can use the container if you need to access your theme classes
		// $this->get_container();

		return [
			'my_message'  => 'everything is fine',
			'my_variable' => 'my value',
		];
	}
};

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 {

	/**
	 * @return array<string,mixed>
	 */
	public function get_rest_api_response( WP_REST_Request $request ): array {
		$request_arguments = $request->get_json_params();
		// todo process the request, based on the query arguments available inside the $input array

		// todo you can use the container if you need to access your theme classes
		// $this->get_container();

		return [
			'my_message'  => 'everything is fine',
			'my_variable' => 'my value',
		];
	}
};

Request Authentication

The REST API is available to both authorized users and guests. However, for security reasons, by default REST API ignores the WordPress auth cookie, and treats the request as if it comes from an unauthorized user. E.g. wp_get_current_user()->exists() method inside the request will return false.

If you need to keep the user authorized inside the request, you must create a wp_rest nonce and pass it in the X-WP-Nonce header, as it described in the official WordPress Developer Documentation. In this cases WordPress will respect the user's auth cookie.

Below, we provide the auth example adopted for usage inside the Advanced Views Framework:

1. Create and pass nonce to the template (in view.php or card.php)

// ...
/**
 * @return array<string,mixed>
 */
public function get_variables(): array {
  return [
    "my_block_nonce" => wp_create_nonce( 'wp_rest' ),
  ];
}
// ...

2. Define nonce as a JS window variable (in Twig or Blade template)

<!-- ... -->
<script>
window.my_block_nonce = "{{ my_block_nonce }}";
</script>
<!-- ... -->

3. Use nonce in the request headers (script.js)

// ...
await fetch('/wp-json/advanced_views/v1/{view|card}/{6630e2da1953e}', {
 method: 'POST',
 headers: {
  'Content-Type': 'application/json',
  'X-WP-Nonce': window.my_block_nonce,
},
// ...

Example of Ajax 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 View 
            '_viewId': '6630e2da1953e', // you can learn ID from the shortcode
            // todo put your Card ID or comment if it's a Card 
            '_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!',
		];
	}
};

Request Authentication

Ajax is available to both authorized users and guests. Unlike the REST API, Ajax does not ignore the WordPress authentication cookie, so it sets up the current user out-of-the-box without requiring any extra actions.

Last updated