alezhka
alezhka

Reputation: 758

rails ajax request

I have a problem when sending the Ajax request. When you click on the link request is sent to the server 3 times and the answer did not come.

Why the request is sent three times to undermine?

Where did I go wrong in the formation of a query?

code:

run.html.erb

...
<%= link_to "Next", "#", :id => 'next', :class =>
...

run.js.erb

(function(){

  $("#next").click(function(){

    $.ajax({
      type: 'POST',
      url: '/engine/tff',
      success: function(data){
        alert("ok");
        $("#question").html(data);
      }
    });


    return false;
  });
});

controller

def tff
    respond_to do |format|
      format.js render :text => "hello"
    end
end

Upvotes: 1

Views: 3488

Answers (2)

Baz1nga
Baz1nga

Reputation: 15579

I am guessing the click event is being bound multiple times probably cos the script is being called multiple times. Not sure what is the reason for the multiple calls as I am not familiar with rails.

what you could do to avoid it is unbind the click event before binding it or use the on api.

function ajaxRequest(){
    $.ajax({
      type: 'POST',
      url: '/engine/tff',
      success: function(data){
        alert("ok");
        $("#question").html(data);
      }
    });
    return false;
  }

$("#next").unbind("click").bind("click",ajaxRequest);

or

$(document).on("click","#next",ajaxRequest);

also not sure if you were trying to bind on document ready and there is a typo in your code. but it should be wrapped like this:

$(function(){
  $("#next").click(ajaxRequest);
});

Upvotes: 2

DGM
DGM

Reputation: 26979

One thing I ran into recently was that jquery tries to run the result, as the default dataType interprets the .js as a script, not text. You might need to add a dataType: "text" to the ajax call. I don't see how this translates into three calls though.

I thought returning false was supposed to prevent the click from moving on, but perhaps it is better form to use preventDefault() as apneadiving suggests.

Upvotes: 1

Related Questions