views:

56

answers:

4

Given:

<%=form_for [:project, @note], :remote => true do |f| %>

I'd like to create a jquery bind that automatically saves every few seconds. I'm not worried about the timing part yet, just how to use jquery to submit the form automatically (ie, not submit button click by the user.)

I tried this, but it isn't working. Suggestions?

$('form[data-remote]').live('submit', function (e) {
    alert(1);
    e.preventDefault();
});

Thanks!

+2  A: 

$('form[data-remote]').submit() will submit the form.

shoebox639
Thanks but that didn't work. How do I trigger the AJAX submit?
TheExit
Oh, but you said that you weren't worried about the timing part. I thought you knew how to set interval events. Well the other answers should answer that.
shoebox639
A: 

So you are talking about something like Autosave, right?

Maybe you want to specify a Javascript interval to this. An example could be:

var autosave = window.setInterval("autosaveForm()", 1000);

function autosaveForm() {
  $('form[data-remote]').submit();
}

What this does is to call autosaveForm() every second and submits the form. To stop the autosave you could just use clearInterval like this:

window.clearInterval(autosave);

I hope this helps.

Max Schulze
thanks Max. I have the autosave down, no issue there. I don't have down being able to ajax submit the form, witha seperate function other than the SUBMIT button generate by Rails 3.
TheExit
Yes that's because Rails UJS is binding the actions directly to the form, if you look into the rails.js file of your application you can see how that works (should be line 76). To trigger a save you should just do $('form[data-remote]').trigger('submit');Is that what you where looking for?
Max Schulze
A: 

Start with setInterval:

  setInterval(transmit, 3000);

Which calls this function:

function transmit(){
 // get the form field data
 var params = {
   formField1:$("input#formField1").val(),
   formField2:$("input#formField2").val()
 }

 // make the ajax call
 var url = "/controller/action";
   $.post(url, params,
     function(response, status){
     //display results(response, status);
   });
}
Hollister
A: 

What version of jQuery are you using? Are you using IE? The early versions of live() didn't work with IE for form submits. (See http://github.com/rails/jquery-ujs/issues/issue/8)

I think I ended up using this:

if (jQuery.browser.msie){
    $("form[data-remote]").delegate("input[type='submit'],button[type='submit'],input[name='commit']", 'click', function(e) {
        $(this).parents("form[data-remote]").submit();
        if(e.preventDefault) e.preventDefault();
    });
}

in a project.

monocle