• Resolved islp

    (@islp)


    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 callback reminderManager fires. BUT it doesn’t work as intended, since it doesn’t receive the POST data. Can you help me understand why?

    • This topic was modified 4 years, 4 months ago by islp.
    • This topic was modified 4 years, 4 months ago by Jan Dembowski. Reason: Formatting. Badly
Viewing 7 replies - 1 through 7 (of 7 total)
  • You must send string name=value+hi (+ is percent encoding send of one space blank) to be visible at $_POST php code or it is empty array ??
    https://developer.mozilla.org/it/docs/Web/API/XMLHttpRequest/Usare_XMLHttpRequest#Inviare_form_e_caricare_file Method: POST; Encoding type: application/x-www-form-urlencoded (default):

    • This reply was modified 4 years, 4 months ago by autotutorial.
    • This reply was modified 4 years, 4 months ago by autotutorial.
    • This reply was modified 4 years, 4 months ago by Yui.
    Thread Starter islp

    (@islp)

    @autotutorial I think you were trying to answer another question, because your reply is completely wrong ?? Don’t worry, it’s not a big problem. ??

    Thread Starter islp

    (@islp)

    I packed in a zip a minimal non-working example:
    https://www.dropbox.com/s/i4otus4w19mhiou/w-userpanel.zip?dl=0

    If you want to give it a try, you have to change a couple of addresses:

    1. line 8 in sendData.js;
    2. line 136 in w-userpanel.php;

    The directory should be uploaded in the plugins folder, then the plugin should be activated.

    Once activated, in the left menu of the admin area, you should find a ‘W Panel’ item: click it and you find a button. When you click the button you are sending JSON to the endpoint.

    You should notice (check the developer tools) that the nureminderManager function correctly fires but POST data is empty.

    Moderator bcworkz

    (@bcworkz)

    I think autoturoial’s reply does apply to this. You are sending JSON data without any “name” parameter for PHP to utilize as a key in its $_POST array, hence you get an empty array in PHP. The data sent should be in the form “name=data&name2=more-data”. The data needs to be URL encoded if it has non-alphanemeric chars besides - _. Use application/x-www-form-urlencoded content type. autotutorial’s link in English:
    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files

    I know you are not sending form data, but your submission needs to look like form data for PHP to handle it as expected.

    Thread Starter islp

    (@islp)

    @bcworkz I have another plugin of mine: I do the same, identical thing and it just works ??

    Thread Starter islp

    (@islp)

    @bcworkz I modified my example to accept ‘application/x-www-form-urlencoded’: same issue

    Thread Starter islp

    (@islp)

    @bcworkz @autotutorial I’ve got it working! The main error is in the reminderManager function (having it changed multiple times and ran out of coffee too… I left there something that absolutely makes no sense).

    The function receives POST data in the format of a WP_REST_Request. This one is a WP built-in object. To get the JSON contained inside this Object you need to call $data->get_json_params() (it returns a plain array).

    Clearly, my file_put_contents2 function did not expect an array as the second parameter, so the function failed to write the file. If you want to write the JSON to a file you must first json_encode the array returned by get_json_params.

    So, finally, if anything works, why did I say that I received no POST? Because, for some unknown (to me) reason, this suddenly started working after I moved the entire rest-related code to the top of the plugin file.

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Custom REST endpoint doesn’t receive POST data’ is closed to new replies.