Programatically submit a remote form?

What’s the best way to programmatically submit a remote form generated using the new form_with syntax? It seems making the form a target, and attempting to submit the form directly doesn’t trigger an XHR form submission, but treats it as local submission.

I’ve seen examples online of instead making the form’s submit button a trigger, and calling the .click() function on it. This will probably work for most scenarios, but in some instances there is no submit button.

Example:

.row.ticket{data: { controller: 'tickets' } }
  = form_with url: update_cart_path, html: { data: { type: "html", action: "ajax:success->tickets#onPostSuccess", target: 'tickets.form' } } do |f|
    = text_field_tag "[ticket][quantity]", ci.quantity, data: { action: "input->tickets#update propertychange->tickets#update" }
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "quantity", "form" ]

  onPostSuccess(event) {
    console.log("success!")
  }

  update() {
    this.formTarget.submit();
  }
}

Found it:

import Rails from "rails-ujs";
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "quantity", "form" ]

  onPostSuccess(event) {
    console.log("success!")
  }

  update() {
    Rails.fire(this.formTarget, 'submit')
  }
}
7 Likes