Class: SimpleAjaxForm::RequestHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_ajax_form.rb

Class Method Summary collapse

Class Method Details

.enable_class_use_on_forms_htmlObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/simple_ajax_form.rb', line 9

def self.enable_class_use_on_forms_html
  "
    <script>
      document.addEventListener('turbo:load', function() {

        let form_elements = document.querySelectorAll('.ajaxForm');

        form_elements.forEach((element)=>{
          element.replaceWith(element.cloneNode(true));
        });

        form_elements = document.querySelectorAll('.ajaxForm');

        form_elements.forEach(function(form_element){
          form_element.addEventListener('submit', function (event) {
            event.preventDefault();

            let element = this;
            let form_url = element.getAttribute('action')
            let form_method = element.getAttribute('method')
            let form_body = new FormData(element)

            fetch(form_url,
                  { method: form_method,
                    body: form_body }
            ).then(res=>res.text())
            .then(data=>eval(data));

          });
        });
      });

    </script>
  ".html_safe
end