Skip to content
This repository was archived by the owner on Feb 4, 2025. It is now read-only.
This repository was archived by the owner on Feb 4, 2025. It is now read-only.

Unable to add to the params after the form has been submitted #5

Description

@DannySantos

The before event acts like the beforeSend event in jquery-ujs and rails-ujs, meaning you're unable to modify form fields or the params in the before hook.

We have gotten around this by adding a new event, but we didn't want to break the naming convention so have had to change the hanami-ujs before event to beforeSend.

I'm not sure what this means for this gem, or whether you would want to make an update that would break existing apps, but here's a summary of the changes we made:

document.addEventListener('ajax:before', function (e) {
  data = e.data;
});

document.addEventListener('ajax:beforeSend', function (e) {
  var token = CSRF.token(), xhr = e.detail;
  if (token)
    xhr.setRequestHeader('X-CSRF-Token', token);
});

------------

document.addEventListener('submit', function(event) {
  var form = event.target;

  if (matches.call(form, 'form[data-remote]')) {
    var before = new CustomEvent('ajax:before', {bubbles: true});
    form.dispatchEvent(before);

    var url = form.action;
    var method = (form.method || form.getAttribute('data-method') || 'POST').toUpperCase();
    var data = new FormData(form);

    if (CSRF.param() && CSRF.token()) {
      data[CSRF.param()] = CSRF.token();
    }

    if (LiteAjax.ajax({ url: url, method: method, data: data, target: form })){
      event.preventDefault();
    } else {
      return true;
    }
  }
});

------------

var beforeSend = new CustomEvent('ajax:beforeSend', {detail: xhr, bubbles: true});
target.dispatchEvent(beforeSend);
xhr.send(data);

return xhr;

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions