Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Form responses must redirect to another location

I need to render an html code I receive from an API.

In Rails 6 : I was doing this in my controller, and it was working fine. I called the webservice I received the response, and I was redirected to the code generated by the render. Fine !

class GatewayController < ApplicationController
  def new
    init_gateway_call
  end

  def create
    call_gateway
    render_gateway_response
  end

  private

  ...

  def render_gateway_response
    render(html: @gateway_response.message.html_safe)
  end
end

new.html.erb :

<%= form_with url: gateway_path, local: true do |f| %>
  ...
<% end %>

And no : create.html.erb

** Rails 7 **

I call the webservice. I get the answer but my page idle and I get this error.

Error: Form responses must redirect to another location at FormSubmission.requestSucceededWithResponse (application-0f0c10fb8f5683e32fc53a93a8a323c328de61682ca16fb65a6a2b8a3ba5d087.js:1614) at FetchRequest.receive (application-0f0c10fb8f5683e32fc53a93a8a323c328de61682ca16fb65a6a2b8a3ba5d087.js:1390) at FetchRequest.perform (application-0f0c10fb8f5683e32fc53a93a8a323c328de61682ca16fb65a6a2b8a3ba5d087.js:1374)

So far, I tried:

# GatewayController
respond_to :create, format: :html, gateway_response: @gateway_response.message.html_safe
<%= gateway_response %>

Without success ... Do you have any idea? Otherwise it is going to be a long weekend ^^

like image 204
user15829831 Avatar asked Sep 04 '25 16:09

user15829831


2 Answers

Setting data: {turbo: false} will cause the page to reload entirely. This takes away the entire point of turbo which is to reduce page reloads.

The reason the error occurs is because Turbo expects a 303 redirect response. The solution is to have the server respond with 422 or 500 status code when you are not redirecting.

if save
redirect_to root_path
else
render :new, status: 422

You can read about this here: https://turbo.hotwired.dev/handbook/drive#redirecting-after-a-form-submission

Of course, if you want the page to reload, you can use data-turbo: false

like image 59
def avi Avatar answered Sep 07 '25 17:09

def avi


I figured it out you while posting my question. The error message seems like a Turbo error. I had to had data-turbo false to my form.

<%= form_with url: gateway_path, local: true, data: { turbo: false } do |f| %>
  ...
<% end %>

And keep my controller like it was.

render(html: @gateway_response.message.html_safe)

Happy upgrade anyone

like image 40
user15829831 Avatar answered Sep 07 '25 17:09

user15829831



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!