Rails 3.1 ajax: handling success

So, I play with CoffeeScript, Rails 3.1 is all good. I have a resource with all the usual route indexes, showing, creating, editing, updating, destroying.

There is a form in the index view that uses :remote => true as follows:

 <%= form_for @todo, :remote => true do |f| %> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> 

In the controller to create, I have the following:

 def create @todo = Todo.new(params[:todo]) respond_to do |format| if @todo.save format.html { redirect_to @todo, notice: 'Todo was successfully created.' } format.json { render json: @todo, status: :created, location: @todo } format.js {render json: @todo } else format.html { render action: "new" } format.json { render json: @todo.errors, status: :unprocessable_entity } end end end 

I try not to use .js.erb views as I would rather handle the returned JSON and do all the fancy additions to the todo list and so on. (It just feels cleaner for me).

In my todos.js.coffee, I used the following:

 $(document).ready -> $("#new_todo") .bind "ajax:success", (event, data) -> alert("Ajax SUCCESS!!!") 

(Yes, just typing to open a warning window doesn’t work) I tried downloading, but just can’t trigger this event. The request succeeds and a new todo is added.

Any help with this would be greatly appreciated. Thanks

+4
source share
2 answers

Started pouring rails.js and wondered if any of the ajax: callbacks went up.

It turned out that they were good before sending and error ... freeze ... error? How could this happen? Creating a new todo is successful, the answer is the JSON that I expect. But when going through the callback code, I notice an Invalid label error.

A quick google later leads me to this post http://blog.seqmedia.com/?p=484

It turns out that JSON returns as a string, Firbug got this and parsed it correctly so that I can check the answer. However, rails.js and js did not know how to process the string at all, and threw the above error (quite quietly, I can tell).

The solution was in response_to

 format.js {render json: @todo, content_type: 'text/json' } 

A little thanks to Trevor Burnham (like BTW) for his help, and to Amy from serial media , whose blog post ultimately gave me a solution.

+8
source
  • What is #new_todo ? Is there an element with this identifier? Make sure $('#new_todo').length > 0 in your code, and that this is the right element to bind your event handler to.
  • What is ajax:success ? The jQuery API defines an ajaxSuccess event (see Ajax Events docs ), but I have never seen a colon version before.
-1
source

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


All Articles