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 anothe开发者_运维问答r solution, please comment to let me know and I'll post the relevant code.
Thanks guys!
$(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
First of all, $('#post_form form[data-remote]').submit()
will do a full submit, and the user will be sent to the action
page. What you want to do is an AJAX post.
Secondly, you don't want to traverse the DOM again every minute (every time you POST). You should cache the form in a variable, so that you can re-use it later.
Here's how you'd go about it:
$(document).ready(function() {
var $form = $('#post_form form[data-remote]'),
href = $form.attr('href');
setInterval(function() {
$.post(href, $form.serialize() + '&draft=true');
}, 60000);
});
精彩评论