Jseb
Jseb

Reputation: 1934

How to add javascript upon ajax response rails

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.

Upvotes: 0

Views: 144

Answers (1)

Scott Norvell
Scott Norvell

Reputation: 128

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!

Upvotes: 3

Related Questions