Gutenberg – how to correctly perform ajax request on backend

I have simple block with server-side rendering on frontend.

PHP:

register_block_type( 'some/block', array(   
    'render_callback' => 'render_my_block',
    'attributes' => array(
        'stuff' => array(

        )
    )
));

function render_my_block( $attributes ) {
  // $attributes['stuff']
  return '<h1>Hello frontend</h1>';
}

Which works, but I also need to render it as a preview in admin area, so I add JS:

registerBlockType( 'some/block', {

    title: 'Some block',

    attributes: {
        stuff : {

        }
    },

    edit( { className, attributes, setAttributes } ) {
        return (
            <Fragment>
                <SomeInput />
                <SomeOtherInput />
                <Preview>
                    // I need to get contents of PHP function render_my_block here, 
                   // based on current attributes.stuff
                </Preview>
            </Fragment>
        );
    },

    save( { attributes } ) {
        return null; // server side
    }

} );

My question is – what is the correct way to fetch this data? Should I just use wp_ajax_ callback/filter? Or Gutenberg has some better way to handle this?

I already checked how default “Latest Posts” block works – it uses Rest API to get post IDs and titles and then renders them via react. But for my case I just need to return simple HTML string.

1 Answer
1

If you wish to do it this way, you need to use the <ServerSideRender /> component in your edit method.

Here’s a basic implementation, based on the PHP block registration code you provided.

import { ServerSideRender } from '@wordpress/components';

registerBlockType( 'some/block', {

    title: 'Some block',

    attributes: {
        stuff : {

        }
    },

    edit( { className, attributes, setAttributes } ) {
        return (
            <Fragment>
                <SomeInput />
                <SomeOtherInput />
                <ServerSideRender
                    block="some/block"
                    attributes={ {
                        stuff: attributes.stuff
                    } }
                 />
            </Fragment>
        );
    },

    save( { attributes } ) {
        return null; // server side
    }

} );

The <ServerSideRender /> component will enable you to call the render_callback provided when originally registering the block in PHP in your edit template. The attributes object passed to the component will be provided as the sole function parameter passed to the callback.

Full disclosure, the WP Codex says this about using the <ServerSideRender /> component:

Server-side render is meant as a fallback; client-side rendering in JavaScript is always preferred (client rendering is faster and allows better editor manipulation).

Leave a Comment