Stimulus Discourse

How to get redirect working after a remote form?

#1

I have a Rails remote form where I handle the response from the server with Stimulus, as described in this article.

In a nutshell the form has a data-type="html" and a data-action="ajax:success->mycontroller#onSuccess ajax:error->mycontroller#onError". As far as the Rails controller is concerned, all requests and responses are HTML format, not JS. In my Stimulus controller I update the page with html from partials sent by the Rails controller action. Here’s an excerpt from my Stimulus controller:

onSuccess(event) {
  const [data, status, xhr] = event.detail
  this.element.innerHTML = xhr.response
}

However in some cases I want the server to redirect the browser to a new page, instead of rendering a partial. In the Rails controller action I’m using a normal redirect_to foos_url for this. But no matter what I try, I can’t stop my Stimulus controller from taking the rendered foos_url page and sticking into my existing page via the this.element.innerHTML = xhr.response line above.

As far as I can tell my Stimulus controller doesn’t even see the redirection occur; I’ve been logging the status codes it receives and they are never (302) Found.

Any help would be much appreciated!

Yours,
Andrew Stewart

0 Likes

#2

The solution turned out to be changing my Rails controller action from this:

redirect_to foos_url

…to this:

render js: "window.location='#{foos_url}'"
0 Likes