0

I am trying to add Ajax, so far I am able to add a javascript response, however I can't add a template.

Here my javascript

application.js

$("#new_role").on("ajax:success", function (e, data, status, xhr) 
{
    $("#newRoleForm").hide(1000);
    return;
}).bind("ajax:error", function (e, xhr, status, error) 
{
    return alert("Error");
});

Here my controller

  def create
    @role = Role.new(params[:role])

    respond_to do |format|
      if @role.save
        format.html { redirect_to roles_path, notice: 'Role was successfully created.' }
        format.json { render json: @role, status: :created, location: @role }
      else
        format.html { render action: "new" }
        format.json { render json: @role.errors, status: :unprocessable_entity }
      end
    end
  end

Now i see a lots of comment stating I should add create.js.erb, but if i just create one and place alert(...); It does get executed. I have modified my form to be ajax remote => true. But i am not sure what i am doing wrong.

1 Answer 1

3

It's not exactly clear what you are asking here, but if you want Rails to respond with javascript (a very powerful feature of rails), in the above example add something like:

format.js { render 'create' }

Then put a create.js.erb file in the appropriate folder. (probably 'roles'). Here you can update your dom, etc. using javascript/jquery with the help of rails. The advantage is that you have access to all of your helpers and partials!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.