Gutenberg – how to correctly perform ajax request on backend

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