How to submit a form and an update item on a page without an update, in Rails 4

I have a lot of problems trying to do something that, in my opinion, would be fairly simple.

I have a list of items, say todos. At the bottom of this list, I have a text box where I add new items to this list. I want to make sure that new elements are added to the bottom of this list dynamically, without a full page refresh, for example, in the chat window.

I made a submit form remote: trueand successfully submitted it without reloading the page, but I can’t get a new item that will be displayed at the bottom of the list at the same time. I need to refresh the page to see the changes.

I tried several different approaches that I found on SO (there is no dearth of similar issues), as well as on the Internet and even in the Sync stone, but each of them had errors and problems, and I could not get any for the correct operation. Each of them may be his own question. So instead, I ask: is there a “recipe” that will definitely implement this in Rails 4?

+4
source share
3 answers

let's say you now have a custom form to submit,

<%=form_for @user,remote: true%><%end%>

And you also have a controller,

UsersController

In your controller you have a function,

def create
  #something
end

which is for the form.

the only thing you need is to change the function, for example

def create
  #something
  respond_to do |format|
    format.js
    format.html
  end
end

, view/users/, create.js, js, , .

:

http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#form-for

+6

, . :

  • AJAX ,

  • / , JSON

  • success AJAX / ,

:

model.js

$(function() {
  $("#submit_button").on("click", function(event) {
    event.preventDefault();
    $.ajax({
      type: "POST",
      url: "your_controller_url",
      data: "your_form_data"
      success: function(result) {
        // Append the result to a table or list, $("list").append(result)
      },
    });
  });
});

controller.rb

def your_action
  # Do your stuff
  # return JSON to the ajax call
end

, . . ( js.erb)

+3

You can see the changes using javascript. For example, consider a Mycontroller controller with an action index and you submit the form by index. Then create a file in the views my_controller / index.js.erb

To reflect the changes, use javascript in this template. A definitely remote sends an ajax call, so to see the changes, you will need some javascript manipulation.

thank

0
source

Source: https://habr.com/ru/post/1533783/


All Articles