Tomato
Tomato

Reputation: 438

Rails ajax executes many times

OK, so I've built a Rails app in which I have some controller which receive data from a form on homepage:

class UsersController < ApplicationController
  def some_method
    ...
    respond_to do |format|
      format.js { render "some_method_first" }
    end
  end
end

And inside some_method_first.js, I got:

$("#some_id").prepend("<section id='notice'>example!</section>");
$(function () {
  $("#notice").delay(500).fadeIn('slow', function () {
    $(this).delay(2500).fadeOut;
  });
});

The tricky part is when I try to input something on the homepage and submit, the first time it's fine, but second time, two "example!" appear, and third time, three "example!" section appear...

I am been driven crazy... Can anyone offer me some clue?

Thanks ahead!

Upvotes: 0

Views: 96

Answers (1)

Jeff B
Jeff B

Reputation: 30099

Looks like you are adding a new section each time. If you don't refresh, the old ones will still be there, so you just keep prepending another one.

You need to check if #notice already exists, or better, just delete it each time:

$("#notice").remove();
$("#some_id").prepend("<section id='notice'>example!</section>");

Upvotes: 1

Related Questions