Question

I am trying to autosave a form for the Post#new action. Every minute or so, I want to POST to Post#autosave and then I'll check for first_or_create and save/updated the record in the Posts table. My problem though is, I can no longer access the POST params from the form. I am trying to do it like so:

$(function() {
  if ($("#new_post").length > 0) {
    setTimeout(autoSavePost, 60000); 
  }    
});

function autoSavePost() {
  $.ajax({
    type: "POST",
    url: "/posts/autosave",
    dataType: "script",
    success: function(data) {
      console.log(data);
    }
  });
  setTimeout(autoSavePost, 60000);
}

I have this route:

post 'posts/autosave', as: :autosave_post_path

The problem is, the server log shows the params hash as only containing :action and :controller. How can I access the equivalent of what would have been sent as part of the POST data.

Was it helpful?

Solution

You need to pass the data param as well, via serialize method:

$.ajax({
  type: "POST",
  url: "/posts/autosave",
  data: $("#new_post").serialize(),
  dataType: "script",
  success: function(data) {
    console.log(data);
  }
});

OTHER TIPS

Take a look at the serialize() function: http://api.jquery.com/serialize/ : You can use it to create an array of data to pass to your controller as parameters.

So, I am Explaining the new Form Script

function autoSavePost() {
  $.ajax({
      type: "POST",
      url: '/quotes',
      data: $("#new_post").serialize(),
      dataType: "script",
  });
}

Send the Post Request to the Controller which just render the edit form after inserting the Object in DB, or better say after persisting the Record.

After the Edit Page is Rendered we wrote a Script there to just update the object after some Interval

function autoSavePost() {
    $.ajax({
      type: "PATCH",
      url: "/post/<%= post.id %>",
      data: $("#edit_post").serialize(),
      dataType: "script",
      success: function(data) {
        console.log("data")
      }
    });
    setTimeout(autoSavePost, 60000);
  }

So, this approach is quite helpful and its a fully Working Auto Save Form Feature and it can be implemented on any type of Object. Thanks !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top