LOCKLOCK
LOCKLOCK

Reputation: 351

Rails Autosave Forms with jQuery/AJAX

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.

Upvotes: 2

Views: 1136

Answers (1)

sourcx
sourcx

Reputation: 974

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!

Upvotes: 1

Related Questions