javascripthtmlformsform-submityandex-metrika

How to send the form with submit event instead of AJAX post?


I use Yandex.Metrika to track user activities on my site (like Google Analytics does). It has an option to track how user works with html forms - what he/she inputs there, how much time spends on each field etc. (link in Russian). But in order to work properly, it requires to submit the form with submit event.

I have the following code:

<form class="form-horizontal" role="form" id="utsDetails">
...
<button type="button" id="calc" name="calc">Calculate</button>
</form>

<script type="text/javascript">
   $("#calc").click(function() {
      $.ajax({
        type: 'POST',
        dataType: 'json',
        data: {
           // all utsDetails form fields are there
        },          
        beforeSend: function(){
           // ...
        }
      })
      .done(function(data, textStatus, jqXHR) {
          // ...
      });

Is there any way to modify my code to keep the functionality unchanged (i.e. page shouldn't be reloaded on button is pressed, result should be received as JSON, beforeSend and done functions should be executed etc.), but to send the form data with submit?


Solution

  • The following changes helped me:

    <form class="form-horizontal" role="form" id="utsDetails" method="POST" action="/"> <!-- added method and action -->
    ...
    <button type="submit" id="calc" name="calc">Calculate</button> <!-- replaced  type with "submit" -->
    </form>
    
    <script type="text/javascript">
       $("#utsDetails").submit(function() { // instead of $("#calc").click(function() {
          $.ajax({
            type: 'POST',
            dataType: 'json',
            data: {
               // all utsDetails form fields are there
            },          
            beforeSend: function(){
               // ...
            }
          })
          .done(function(data, textStatus, jqXHR) {
              // ...
          });
          return true; // to avoid page reload