Saving data from block editor to the database

I’m developing a wordpress plugin and looking to save data entered in a block to a mySQL table. That’s it. But how can data be sent from the block editor to the server side? I’ve spent two weeks looking for the appropriate technique and no joy.

The scenario is simple:

    registerBlockType("bla/quote-block", {   //...
        attributes: { quoteAtt: { type: 'string' } },
        edit: function(props) {
            props.setAttributes( { quoteAtt: getQuote() } );
            // ?? Send props.quoteAtt to the server ??
        }

I’ve found how to use AJAX + jQuery + wp_localize_script but that method apparently is only suitable for sending data from the front end (eg form data). The REST API is horrendously complex and all the documentation is about reading post [meta] data, not about saving data into a table.

Thank you!

1 Answer
1

I’ve found a solution using Ajax with native Javascript as follows:

// Filename send2server.js
const sendToServer = function() {
   /* Prepare the object to be sent: ********************************************************************/
   var params = new FormData();
   params.append('action',   'update_sql');                // update_sql is implemented in PHP (see below)
   params.append('quoteAtt', props.attributes.quoteAtt);   // The actual data

   /* Create the Ajax connection object: ****************************************************************/
   var request = new XMLHttpRequest();
   request.open('POST', ajax_object.ajax_url, true);       // ajax_object.ajax_url defined in PHP (below)
   request.send(params);                                   // Send request to server
}

On the server side, the following functions receive the request in the following manner:

// File plugin.php
function load_ajax_script() {
    wp_enqueue_script(
        'send2server',
        plugins_url( 'send2server.js', __FILE__ ),
        array(),
        filemtime( plugin_dir_path( __FILE__ ) . 'send2server.js' )
    );

    wp_localize_script(                                // make ajaxurl available to Javascript
        'send2server', 
        'ajax_object', 
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) 
    );  
}
add_action('init', 'load_ajax_script');


function update_sql() {                                // Invoked by request.send()
    $received = $_POST["quoteAtt"];                    // Contents of quoteAtt
    // ...
}
add_action('wp_ajax_update_sql', 'update_sql');        // 'update_sql' matches the 'action' in params

Is this the best solution? I don’t know, but it works.

Leave a Comment