-2

This question is very similar to this one but my problem wasn't adressed entirely.

So I have indeed a form with many buttons. The buttons each have a different commit message : using rails submit_tag helper generates HTML like

<!-- AJAX buttons -->
<input type="submit" value="Preview" name="commit">
<input type="submit" value="Send me a preview" name="commit">
<!-- POST buttons -->
<input type="submit" value="Send to me" name="commit">
<input type="submit" value="Send to all" name="commit">

The form is originally non-AJAX, but I want to submit it via AJAX with the top two buttons. BUT (and this problem isn't addressed in the aforementionned question), I must also make sure I do pass the right commit message in the parameters.

Using a code like this one

<% text = "Preview" # etc.
<%= submit_tag( text, 
        onclick: " 
            var form = $(this).closest('form');
            form.data( 'remote', 'true' );
            form.submit();
            form.removeAttr('data-remote');
            return false") %>

Does not work because calling form.submit() will submit the form without the commit message of the button being pressed.

The form is meant to be used multiple times : an example scenario would be

  • User wants to send a customisable email
  • User fills a form, click on the "Preview" button (AJAX), this produces a quick preview. He can repeat as many times as he needs.
  • User wants to get a private preview, he clicks the "send me a preview", so he receives an actual email (still AJAX)
  • User is happy with everything and wants to send the email. He therefore clicks one of the POST buttons that will change the page and show a confirmation message
Community
  • 1
  • 1
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

0

Alright, here is the solution I found

Rails view (ajax here is just a boolean whether we want the button to perform in AJAX or not)

<%= submit_tag( text, data: data, 
    onclick: (ajax ? "ajaxSubmit(event)" : ""), class: html_class) %>

The javascript code

function ajaxSubmit(e){
    e.preventDefault();
    var target = $(e.target)
    var form = target.closest('form')
    var tmp = form.data('remote')
    var input = $('<input />').attr('type', 'hidden')
        .attr('name', "commit")
        .attr('value', target.val())
        .appendTo(form);
    form.data('remote', true)
    form.submit()
    if(!tmp){
        form.removeAttr('data-remote');
    }
    input.remove()
    return false;
}
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164