Stimulus Discourse

Ajax:success without form action

Hello Stimulus users,

I try to use Sortablejs with stimulus + Rails backend.


this is my prototype.

when drag and drop end, I use ajax with Rails.ajax in stimulus controller.

    sortable = Sortable.create(this.collectionListTarget, {
      handle: ".drag-handle",
      animation: 150,
      swap: true,
      onEnd: (/**Event*/evt) => {
        var itemEl = evt.item;  // dragged HTMLElement
        console.log('on End')
        const data = 'collection[title]=UJS 테스트'
            url: "/collections",
            type: "post",
            contentType: 'html',
            success: function(data) {
              const event = [null, null, { response: data }]
              return true
            error: function(data) {
              console.error('error => ', data)

create collection is for testing. ajax call is always succeed. but I don’t know where to set action for sort.

      <div data-controller="collections">
        <button data-action="click->collections#toggle" data-target="collections.toggler">
          create new collection
        <%= form_with(
          data: { type: "html", target: "collections.form", action: "ajax:success->collections#onAddCollection ajax:error->collections#onAddCollectionError"},
          class: "d-none"
          ) do |form|
            <%= form.text_field :title, data: { target: "collections.input" } %>
           <input type="submit" value="Submit">
        <% end %>
        <ul id="collections" class="list-unstyled" data-target="collections.collectionList">
          <%= render @collections %>

where is the right place for stimulus action? I don’t know where to set ajax:sucess handler.

    document.body.addEventListener('ajax:success', function(event) {

this event listener only works when form action success.

I use custom action with, it works well. But I did not know it is best practice.