0

I have a rails form that updates a devise user. I want to submit the form silently because it's part of a wizard the user is going though. Even with remote: true on the form, triggering a submit action with javascript causes the page to reload. Here is some code:

<%= form_for(@current_user, as: resource_name, url: registration_path(resource_name), html: { method: :put }, remote: true) do |f| %>

and the javascript is:

btnContinue.addEventListener("click", (e) => {
  $("#edit_user").submit()
});

I've tried:

  $("#edit_user").submit(function (e) {
    e.preventDefault();
  });

But that doesn't trigger anything.

All I'm trying to do here is submit the form in the background while I send the user to the next step on the same page. Any ideas what I'm missing here?

Arel
  • 3,888
  • 6
  • 37
  • 91
  • 1
    Which version of rails are you using? – Ben Trewern Sep 20 '22 at 23:34
  • Rails version 7.0 – Arel Sep 21 '22 at 02:36
  • 1
    Why don't you do it the Rails way with Hotwired: when the user clicks on "next step" you make a travel to the back end and update the form display with a turbo stream ? What you are doing at the moment is triggering the form submit with JS but your form is still triggered, just like if the user pressed a submit button. If you want to submit async then you have to do a `fetch()` or Ajax in your javascript. You will need to gather all data and pass it as content of your `fetch()`. – Maxence Sep 21 '22 at 09:50
  • 1
    Rails 7.0 doesn't have ujs installed by default. Look here https://stackoverflow.com/questions/70767231/rails-ujs-not-firing-with-rails-7. – Ben Trewern Sep 21 '22 at 13:04
  • Thanks for the suggestions @Maxence. I'm not trying to update anything on the page, just submit the data from the form. I think you're right that the best way to do this is to just submit an ajax request with the data. I was hoping I could just take advantage of the form that was already there. – Arel Sep 21 '22 at 22:07
  • Yeah doing fetch or Ajax is redundant with your form. Then just progress your wizards with turbo frames. Turbo frames basically allow Single Page App concepts and it would suit well a multi-step form or Wizard. Also you can validate each step and return an error if something goes wrong (in case your front end doesn't cover every corner of your inputs) – Maxence Sep 21 '22 at 22:21

0 Answers0