wordpresswordpress-rest-api

How to redirect using a custom wordpress api endpoint after form submission?


I'm using a custom wordpress endpoint that I have defined in functions.php:

add_action('rest_api_init', function () {
    register_rest_route('custom_endpoint', 'submit-application', [
        'methods' => 'POST',
        'callback' => 'submit_application'
    ]);
});

I'm using the endpoint to process some form data sent via jetform builder. After the form data has been processed (various calls to an external api), I would like to redirect to a url that is returned by the api dynamically. Currently the business logic all succeeds, but I cannot for the life of me get the redirect to work. The form submits and displays a message "Form successfully submitted".

function submit_application ( $request ) {

  //Business logic here all succeeds

  $user= send_data($data);

  try {
      return new \WP_REST_Response(
          null, 
          303, 
          array(
              'Location' => $user['url'], 
          )
      );
      
  } catch (Exception $e) {
      return new WP_REST_Response( [
          'status' => 'error',
          'message' => $e->getMessage()
      ], 400 );
  }
}

I've also tried using

    wp_redirect( $user['url'] );
    exit();

The odd thing is I got it to work once, with what I think is this exact code, but suddenly after I continued development it stopped. It is also odd, because when I try the end point via postman instead of the form submission, it seems to receive the redirect correctly as well. Maybe that's indicative of a cache issue? I'm a little new to wordpress so any ideas would be very welcome!


Solution

  • In the end there were two things preventing me from redirecting the client directly from the custom Wordpress endpoint. Here is the redirect code that I included in the end of my endpoint

          return new \WP_REST_Response(
              null, 
              303, 
              array(
                  'Location' => $user['portal_url'], 
              )
          );
          
    

    The first issue was that JetForm was taking control of things and erroring out when the redirect was included for some reason. To fix this I just bypassed JetForm submission by targeting the form element and changing the action to go directly to my custom wordpress endpoint instead.

    <script> 
        let form = document.querySelector('.jet-form-builder');
        form.action = "https://your-endpoint-url.com"
    </script>
    

    The last tidbit is that by doing this bypass I was receiving a nonce error so you either have to add some logic to account for this, or if you don't mind (i.e. you don't consider it a security vulnerability in your use case), just disable "Form Safety" in JetForm.