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

admin2025-01-08  4

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!

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!

Share Improve this question asked Oct 29, 2024 at 18:41 BrendenBrenden 111 bronze badge 3
  • 1 Duplicate of stackoverflow.com/questions/79138372/…. Please post your question in only the most appropriate site. – Caleb Commented Oct 29, 2024 at 19:19
  • 1 @Caleb sorry, assumed they would be different communities. Just trying to figure this out and feeling a bit frustrated. – Brenden Commented Oct 29, 2024 at 19:25
  • Have you tried var_dump( $user['url'] ) to see what it is you're getting? – Tony Djukic Commented Oct 30, 2024 at 15:35
Add a comment  | 

2 Answers 2

Reset to default 1

If you're using javascript to submit the form data to the REST endpoint, then you should handle the redirection at the client side, not at the server with PHP. Read the location header from the response and pass it to window.location to redirect the user somewhere.

Here's a simplified example - not tested, requires fleshing out.

document.getElementById('my-form').addEventListener('submit', (event) => {
    event.preventDefault();

    submitViaRestApi(event)
        .then(response => redirectToLocation(response.location))
        .catch(error => console.error(error));
});

function redirectToLocation(location) {
    // like a mouse click
    // window.location.href = location;
    // or
    // a HTTP redirect
    // window.location.replace(location);
    // Learn about window.location at https://developer.mozilla.org/en-US/docs/Web/API/Location
}

function submitViaRestApi(event) {
    return new Promise((resolve, reject) => {
        // send data to REST endpoint
    });
}

It sounds like the issue might be related to how the response is being handled after the API submission. The 303 status code with the Location header is correct for a redirect, but there may be some form-handling logic that's preventing it from being followed.

A possible solution would be to ensure that after the form submission, the page properly redirects when receiving the API response. You can also try using wp_redirect directly inside your callback, ensuring it's done before returning the response. Here’s an updated version of your code:

function submit_application($request) {

    // Business logic here
    $user = send_data($data);

    try {
        // Direct redirect using wp_redirect
        wp_redirect($user['url']);
        exit();
    } catch (Exception $e) {
        return new WP_REST_Response([
            'status' => 'error',
            'message' => $e->getMessage()
        ], 400);
    }
}

The key difference here is making sure wp_redirect and exit() are executed before sending the response back. If the API endpoint is directly interacting with the front end, this should trigger a proper redirect.

By the way, which hosting are you using? Some hosting providers handle caching and server-side configurations differently, which could affect things like dynamic redirects. I’ve been using Cloudways, and I like how they handle caching and other optimizations while keeping things easy to manage. It might be worth exploring if server-side issues are causing conflicts.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736266173a1099.html

最新回复(0)