POST request not going through?

Question

I’m still trying to see clearly in some aspects of the API.

I have a custom route

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

I have a similar one for GET that works perfectly:

add_action( 'rest_api_init', function () {
  register_rest_route('my-project/v1/', '/form/get/', array(
    'methods' => 'GET',
    'callback' => 'get_form',
  ) );
})

Callback method that returns plain text + “null” (using var_dump, be can use echo):

function post_form($data) {
    var_dump($data);
    return;
}

Alternative callback test method as it was suggested in an answer to another question):

function post_form($data) {
    $data = [ 'foo' => 'bar' ];
    $response = new WP_REST_Response($data, 200);
    $response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);
    return $response;
}

jQuery call:

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

Serialization works well, $.post is reached and then nothing happens forever, the alert line is never reached.

What am I doing wrong regarding this POST?

It’s (I think) not a 404 not found case, I had that but I think it’s corrected now.
There is no JavaScript error in Chrome’s console.

0
TTT 4 months 2020-12-22T09:10:20-05:00 0 Answers 8 views 0

Leave an answer

Browse
Browse