There is a more or less standard form that is tested with Ajax. The problem is that it starts working only from the second time, after reloading the page. Another difficulty is that the code is not mine and I’m not good at figuring out what the problem is.

Link to the form itself: https://www.advantika.ru/test.php

Javascript:

$('.form form').submit(function(e) { if(!! window.FormData){ e.preventDefault(); $form = $(this); $submitButton = $form.find('[name="web_form_submit"]'); $submitButton.addClass('proceed').prop('disabled', true); var formData = new FormData(this); formData.append('web_form_submit', $submitButton.val()); $.ajax( { url: 'https://www.advantika.ru/_formHandler.php', type: 'POST', data: formData, processData: false, contentType: false, cache: false, success: function(response){ $response = $(response); if($response.find('.form-form-note').length > 0){ if('order' == $form.attr('name')){ var checkedServices = []; $form .find('.form-services') .find('[type=checkbox]') .each(function(){ if(true === $(this).is( ':checked' )){ checkedServices.push($(this).attr('data-gtm-val')); } }); var gtmEventLabel = document.URL + '|' + checkedServices.join('.') + '|'; }else{ var gtmEventLabel = document.URL; } dataLayer.push({ 'event': 'adv.event', 'eventCategory': 'formSubmit', 'eventAction': $form.attr('name'), 'eventLabel': gtmEventLabel, 'eventValue': 0, 'eventNonInteraction': false }); $form.find('.form-element input').val(''); $form.find('.form-element textarea').val(''); $form.find('input[type=checkbox]').prop('checked', false); } $form.find('.form-messages').stop().html($response.find('.form-messages').stop().html()); $submitButton.prop('disabled', false).removeClass('proceed'); } }); return false; }else{ $(this).submit(); } }); 
  • Specify - what means - the second time? - xAqweRx
  • When you enter the page for the first time and click on the form submit button (you can not even fill out the form itself) - the form is processed with the page reloading (as if Ajax is not used), and after reloading it works as expected. It is necessary that it work properly entering the page - GL
  • The easiest option is to try changing $('.form form').submit(function(){}) to $(document).on('submit','.form form',function(){ ... } ) - xAqweRx
  • And the code of the form itself is possible? - Vitaliy Shebanits
  • The link can be seen jsfiddle.net/Haseri/zv1p5kLs . I deliberately did not embed the form code in order not to clutter up the message, simply through DevTools (or an equivalent), in theory it is more convenient to look directly at the site)) - GL

1 answer 1

xAqweRx answered the question in the comments, I decided to put it in the answers so that it would be more noticeable:

The easiest option is to try changing $('.form form').submit(function(){}) to $(document).on('submit','.form form',function(){ ... } )