1

I have read this submit a rails remote form with javascript

and none of the solutions seem to work. I just need to run a callback before the submit gets called.

View

<form id="formA" " novalidate="novalidate" action="https://www.demo.com/form.php" accept-charset="UTF-8" data-remote="true" method="post" _lpchecked="1">
...
</form>

JS

var form = document.forms.item(0)

form.addEventListener('submit', async function(e) {
   e.stopImmediatePropagation()
   e.preventDefault();
   ...
   form.submit()
});

My form does not seem to submit with remote: true, so no ajax, I get a html response instead of a js response.

12
  • Can your issue be solved with one of the custom events fired by Rails? For example form.addEventListener("ajax:before", function (event) => { ... }) Commented Feb 26, 2021 at 19:43
  • Good recommendation, but what happened when I have a form that is remote: false? Commented Feb 26, 2021 at 20:17
  • Then the "ajax:before" event does not fire. Since a remote check is made beforehand. Commented Feb 26, 2021 at 20:38
  • My form needs to work both ways, depending on situation. I need to run the call back in both situations remote:true and remote: false. Commented Feb 26, 2021 at 20:41
  • 1
    It does not handle remote: false, for that you'll have to make the remote check yourself. Eg. if (e.target.hasAttribute("data-remote") && e.target.getAttribute("data-remote") != "false") { Rails.handleRemote.call(e.target, e) } else { form.submit() } You might also want to disable the submit-button while your async stuff is being processed, to prevent the user from sending multiple "submit" events. Commented Feb 26, 2021 at 21:18

1 Answer 1

0

It may be too late to answer, but I solved same issue with this code.

form = document.querySelector('#form_id');
form.dispatchEvent(new Event('submit', {bubbles: true})); // you can specify more options in `Event()` for reliability across different browsers.

It is from : https://stackoverflow.com/a/52304806/1529453

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.