2

I know this question has been asked several times but I could not find one post that perfectly solves my problem.

Background: I have a form that are currently being created/updated ajax-ly using Ruby on Rails and jQuery. I need to autosave the form content every 30 sec for every create/update action. Right now, I am focusing on making autosave create form to work.

I have something like below:

#controller method
def create
  @report = Report.create(params)
end

#js
$(function() {
  if ($("#report").length > 1) {
    setTimeout(autoSaveForm, 30000);
  }
});

function autoSaveForm() {
  $.ajax({
    type: "POST",
    url: "report/create",
    data: $("#report").serialize(),
    dataType: "script",
    success: function(data) {
      console.log(data);
    }
  });
  setTimeout(autoSaveForm, 30000);
}

Update: Upon closer inspection, $("#report").serialize() is not working. It is not capturing the form content. I am using cocoon to generate two-layered nested forms. I need to correctly serialize the form content.

Update: replace "#report" to "form" will do. Thanks a lot.

LOCKLOCK
  • 341
  • 1
  • 3
  • 13
  • What is not working? – sourcx Oct 15 '15 at 19:45
  • Hi Frank, the url is not working. – LOCKLOCK Oct 19 '15 at 01:41
  • I'd like to help you out, but I would need a bit more information. It's good practice to also show the error messages that you see (check your browser's developers console). Also, it's nice to explain where you think the problem is at, by stating the things that you've tried already. If you have some more information, please update your original post. – sourcx Oct 19 '15 at 15:09
  • Thanks Frank. I have updated the problem description. It is a problem with form params serialization. Any thoughts? – LOCKLOCK Oct 20 '15 at 17:04

1 Answers1

1

Thanks for updating your question. Although I have the feeling your code is never executed because of this check ($("#report").length > 1) (simply remove the > 1 part for it to work), the real problem is the nesting of forms.

Because nesting forms is not valid (see Is it valid to have a html form inside another html form?) you are unable to target a form contained in another form.

I confirmed it again here https://jsfiddle.net/2tuo3yhv

Does your outputted HTML contain a <form> tag in a <form>? If so, you can only use the outer form to target and save.

Good luck and let me know if you can solve your problem this way!

Community
  • 1
  • 1
sourcx
  • 944
  • 7
  • 22
  • Replace "#report" with "form" and change length > 1 to > 0. Exactly what you said. Now I have another problem - to differentiate autosave with actual submit. Any thoughts? – LOCKLOCK Oct 20 '15 at 18:51
  • Nice! Could you accept my answer as official answer then as well? :) To know which form submitted you will need to use a unique id, e.g. `form#first` and `form#second`. Can you actually select the nested form with the use of cocoon? – sourcx Oct 20 '15 at 19:07