Submitting a form

I need to update the URL a form is submitted according to the value of an input field.
Based on Stimulus and Rails UJS I came out with the following (dummy) code (it doesn’t change the action yet).

<form data-controller="login" data-action="ajax:beforeSend->login#prepareParams" action="/sessions" accept-charset="UTF-8" data-remote="true" method="post">
 ...
</form>


import { Controller } from "stimulus"
import Rails from "@rails/ujs"

export default class extends Controller {
  prepareParams(event) {
    event.preventDefault()
    Rails.fire(this.element, "submit")
    console.log("submitted")
  }
}

But the form is not submitted when I try to do so. I just get “submitted” on my console but nothing happens server-side.

Am I missing anything here?

I’m using Stimulus 1.1.1 and @rails/ujs 6.0.0.

Thanks

If I’m not mistaken your example would cause an endless loop. When the form is submitted, the ajax:beforeSend event is handled in the prepareParams controller method. It attempts to submit the form again, which causes the ajax:beforeSend event to trigger once more, and so on. The form never actually submits. Do you see a lot of “submitted” console outputs that could confirm this suspicion?

Do you mind giving at bit more context on why you want to change the form url based on the value of an input field? Maybe it would be possible to use form data instead of changing the url?

If that doesn’t work for you, it should be possible to change the form action if you listen to the submit event instead of ajax:beforeSend.

<form data-controller="login" data-action="submit->login#prepareParams" ... >
 ...
</form>
prepareParams(event) {
  this.element.action = "/new-url"
}

There’s no need to submit the form programmatically as the event propagates after the form action has been changed.

1 Like