Search code examples
jqueryruby-on-railsruby-on-rails-3autosave

how can I add data to an html form when submitting (autosaving) by jQuery?


I have a form I am submitting by jQuery, to auto-save it. This is in Ruby On Rails 3. My model is a Post that I want to auto-save. The post model is adapted to ignore certain validations if a boolean field (draft) is = true. (If draft is nil, then the validations run)

I use the following code to submit the form at intervals to autosave it.

 $(document).ready(function() {
   setInterval(function() {
     $('#post_form form[data-remote]').submit();
   }, 1000*60); // 1000ms * 60s = 1m
 });

When the form submits by this function, I want to include a variable :draft => true somehow, to ignore validations etc.. How can I add to this javascript to accomplish this? Or is that simply not possible?

If I would have to go into the code rails-wise and do another solution, please comment to let me know and I'll post the relevant code.

Thanks guys!


Solution

  • $(document).ready(function() {
       setInterval(function() {
         var draft = $('#draft');
         if(draft == null)
         {
            $('post_form').append('<input type="hidden" name="draft" id="draft" value="true" />');
           draft = $('#draft');
         }
         draft.val('true');
    
    
         $('#post_form form[data-remote]').submit();
       }, 1000*60); // 1000ms * 60s = 1m
     });
    

    I have updated your code, I have created hidden input text box with the value true and name draft.

    I hope this helps