Custom Ajax & Rest API (Pro)

About the feature

Advanced Views Pro has the Custom_Data feature for Layouts and Post Selections, allowing 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 Ajaxarrow-up-right and REST APIarrow-up-right, 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.

circle-info

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

card.php

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 describedarrow-up-right 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)

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

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

Example of Ajax usage

script.js

view.php

card.php

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