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) {

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:

   var serializedForm = $('#my-project-form').serialize();
    $.post("/wp-json/my-project/v1/form/post/", serializedForm, function(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.

  • Everything you posted works fine for me on WordPress 5.1.1. Sounds like it's time to disable plugins and themes and see if you can reproduce the problem. – MikeNGarrett Apr 12 at 13:45
  • 1
    I found the source of the problem, see the answer I posted. I also edited the question because some information was missing to identified it. – TTT Apr 12 at 14:13

I found that it didn't work because both endpoints used the same route. I expected defining one for POST and one for GET would result in different callbacks, but they apparently conflict with each other.

In a first time, I get the request going through simply by change the namespace for the POST.

Maybe there is a way to define different callbacks far a same namespace , I need to check that.

(Now, I have another problem which is that $data input is empty, but I need to check things and maybe make another question for that.)

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.