11
votes

I have a form that for the most part just submits as a normal form, so I don't want to set in the form_tag the :remote => true option.

However, under certain circumstances I'd like to be able have a javascript function post the form as if it had been posted by :remote => true. What would I need to do in javascript to accomplish this?

5

5 Answers

5
votes

I just tried this which definitely works, if the form has remote => true, just remove the data-remote attribute to submit normally w/ javascript ie

$('input').click(function(){ $('#form').removeAttr('data-remote') });

I'm guessing the opposite would probably work ie if the form doesn't have remote => true just do

$('input').click(function(){ $('#form').attr('data-remote',true)});
33
votes

I'm sorta new to this but here goes...

rails.js (the jquery one at least) defines the following function to catch and submit forms:

$('form').live('submit.rails', function(e) { ... });

If you use the following it should trigger the same function (and if :remote => true, then it wont cause a page reload):

$("#<yourformid>").trigger("submit.rails");

So, if you wanted to submit your form on a select change for example, you could set the above trigger call to the select's :onchange I would imagine.

3
votes

maybe u could try this:

$('#form').submit();
2
votes

If you're using jQuery you could do something like this to have the form auto-post on keyup events, or simplify it to trigger manually:

  $(function() {    
    $("#live_search input").keyup(function() {
        q = $('#search_text').val();
      $.ajax({
          beforeSend      : function(request) { request.setRequestHeader("Accept", "text/javascript"); },
                           // Included so Rails responds via "format.js"
          data          : 'query=' + q,
          success       : function(data, textStatus, XMLHttpRequest) {
                                // alert(textStatus);
                                $("#live_search #results").html(data);
                                },
          error         : function(XMLHttpRequest, textStatus, errorThrown) {
                                // alert(errorThrown);
                                $('#annotation_dialog').html(XMLHttpRequest.responseText);
                                },
          type            : 'POST',
          url                 : '/search/live'
      });
      return false;
    });
});
1
votes

In Rails 5 (which replaces jquery-ujs with rails-ujs), this is how you trigger the handler rails attaches to a form's submit event:

var elem = document.getElementById('myform') // or $('#myform')[0] with jQuery
Rails.fire(elem, 'submit');

(Holy cow did it take me forever to figure that out!)