Rails ajax form submit message

ruby, ruby-on-rails

Solution

You're almost there. The submitted form is processed by the create action, not by new. You've got the syntax right for handling html or js - you just need that in your create action, and a create.js.erb containing the js you want to render.

Your PostsController should have a create function along the lines of

def create
  @post = Post.new(params[:post])

  respond_to do |format|
    if @post.save
      format.html 
      format.js 
    else
      format.html { render :action => 'new' }
      format.js   { render 'fail_create.js.erb' }
    end
  end
end

Create a file named create.js.erb (in the views directory for posts), containing

alert('Hello Rails');

and you should be good to go, for the success case. Create a second file named fail_create.js.erb with whatever javascript you want to render in case of failure (e.g. when the submitted form data doesn't pass your model's validations).

Problem

I am building my first rails application and am new to both ruby and rails. I am trying to render a submit message on a page after a form is submitted via ajax. I have added to my form the :remote => true parameter. However I don't seem to be able to render a message after in my application. As a test I have set up a fresh rails app and generated a posts model and view etc with form using scaffolding. I added the remote :remote => true to the generated form. It submits the data fine to the db. I have read I can just update the controller to include js with format.js, in this case updating posts_controller.rb func to ``` def new @post = Post.new respond_to do |format| format.html # new.html.erb format.js end end ``` A few tutorials have said you can then just add a new.js.erb or create.js.erb (not sure which it should be) in the views/posts folder and this should be executed but nothing happens other than the data being submitted. I have also tried: ``` format.js { render :js => "alert('Hello Rails');" } ``` as a test. I am using rails 3.1 and am at a loss to what I should try next

Original source