Custom REST endpoint doesn’t receive POST data
-
I’m in the process of building a little WordPress plugin.
I registered a REST route this way:
add_action('rest_api_init', function () { register_rest_route( 'mypluginame/v1', '/reminder', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => 'reminderManager', 'permission_callback' => function () { return current_user_can( 'manage_options' ); } )); });
This is the related
reminderManager
function:function reminderManager(WP_REST_Request $data){ $p = file_put_contents2("saved.json", $data->get_json_params()); if($p===false){ return array("fileWritten"=>"KO", error_get_last()); }else{ return array("fileWritten"=>json_encode($data)); } }
In the
footer
of the plugin admin page I have a button.This button simply calls the REST route endpoint, sending a JSON string in an AJAX POST request, through this basic JS:
function sendData(jsonData) { var xhr = new XMLHttpRequest(); var r = "https://www.mydomain.com/wp-json/myplugin/v1/reminder"; xhr.open('POST', r); // myScriptVars is defined in wp_localize_script and it is readable here xhr.setRequestHeader('X-WP-Nonce', myScriptVars.nonce); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 200) { alert('Data saved'); } else { console.log('Failed with status: ' + xhr.status); } }; xhr.send(jsonData); }
What happens: when
xhr.status===200
I regularly see the alert and, at the same time, the callbackreminderManager
fires. BUT it doesn’t work as intended, since it doesn’t receive the POST data. Can you help me understand why?
Viewing 7 replies - 1 through 7 (of 7 total)
Viewing 7 replies - 1 through 7 (of 7 total)
- The topic ‘Custom REST endpoint doesn’t receive POST data’ is closed to new replies.