0

I have this:

add_action( 'rest_api_init', function () {
  register_rest_route('my-project/v1/form', '/post', array(
    'methods' => 'POST',
    'callback' => 'post_form'
  ) );
});

I called it with this and the call gets done and serializedForm is not empty:

$(".my-project-submit").click(function(){
   var serializedForm = $('#my-project-form').serialize();
    $.post("/wp-json/my-project/v1/form/post/", serializedForm, function(data) {
        alert(data);
    });
});

I tried these:

function post_form($data) {

$data is null/empty.

function post_form($data) {
   $data = $request->get_params();

I don't know it $data is null, I just do not receive response ( alert(data) never reached).

    function post_form($data) {
       $data = $request->get_body();

I don't know it $data is null, I just do not receive response ( alert(data) never reached).

All test methods end with

    $response = new WP_REST_Response($data, 200);
    $response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);
    return $response;
}
  • 2
    $request is undefined in your examples so it will never work, the parameter passed to the callback is the request object, but you've named yours $data for some reason, not $request – Tom J Nowell Apr 12 at 15:28
  • Indeed, you should write as answer ;-) – TTT Apr 12 at 15:30
  • Additionally, jQuery serialize generates a URL encoded string, it's not standard JS practice when using POST, and would require additional steps on the PHP end to deserialize – Tom J Nowell Apr 12 at 15:30
  • I would if i knew a full answer at hand, I know it's a part of the issue, but I don't know how to handle the usage of serialize in jQuery here. For reference, PHP should be giving you warning and notice messages in your error log for that code due to the use of an undefined variable, so check you've got your debugging setup right and PHP error logs are working – Tom J Nowell Apr 12 at 15:31
  • How should I do it instead of serialize? (I haven't setup debugging PHP debugging. Long story short, I come from C# where debugging mostly comes in 1 click. Deciding of environment/IDE for PHP developement has been a long headache-process which I'm not sure is becoming stable yet.) – TTT Apr 12 at 15:41
0

Update your function post_form as


function post_form(WP_REST_Request $request)
{
    $data = $request->get_params();
    print_r($data);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.