V
V
vadimstroganov2015-08-16 17:14:37
JavaScript
vadimstroganov, 2015-08-16 17:14:37

Why is there multiple requests on click?

Hello! I don’t understand what the problem is, there is a feedback form, and when you click on the send button, the shipment arrives 1-7 times per click (mail with data from the form arrives 1-7 times per click, respectively)

Form:

<div class="callback-form" id="callback-form">
  <%= form_for :email,
               html: {id: "contact_form"},
               :url => { :controller => 'pages', :action => 'send_mail' },
               :method => "POST",
               :remote => true  do |f| %>
    <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
    <%= f.label :name, 'Ваше имя' %>
    <%= f.text_field :name, :class => 'name', :size => 60 %>
    <%= f.label :telephone, 'Ваш номер телефона' %>
    <%= f.text_field :telephone, :class => 'telephone', :size => 60 %>
    <%= f.label :body, 'Сообщение' %>
    <%= f.text_area :body, :rols => 10, :cols => 60 %>
    <%= submit_tag "Оставить заявку", :class => 'btn-send-form' %>
  <% end %>
  <div id="response"></div>
</div>


Script:
$(document).ready ->
  $("#contact_form").on("ajax:success", (e, data, status, xhr) ->
    $("#response").empty()
    $("#response").append data
   ).on "ajax:error", (e, xhr, status, error) ->
    $("#response").replaceWith ""


In the controller:
Emailer.send_form(params[:email]).deliver_now

In the model:
def send_form(email_params)
    @email = '[email protected]'

    @name = email_params[:name]
    @telephone = email_params[:telephone]
    @message = email_params[:body]

      mail to: @email,
           subject: 'Welcome to My Awesome Site'

  end


But what happens after pressing the button (1 time!)
eef7c0cf28834f949d637c6238473a1a.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
caution, 2015-08-17
@caution

try to deal with turbolinks

S
Sergey Ivanov, 2015-08-17
@Writerim

several handlers hang.
From jquery example (for easy understanding)

<div class="a">
  <div class="b">
    <div class="c">
    </div>
  </div>
</div>

$('.a').click(function(){...})
$('.b').click(function(){...})
$('.c').click(function(){...})

по окончании у вас будет несколько обработчиков на один элемент.

M
maximw, 2015-08-17
@maximw

Попробуйте так:

$(document).ready ->
  $("#contact_form").off("ajax:success").off("ajax:error").on("ajax:success", (e, data, status, xhr) ->
    $("#response").empty()
    $("#response").append data
   ).on( "ajax:error", (e, xhr, status, error) ->
    $("#response").replaceWith ""

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question