javascript – POST request executing 6 times instead of one when clicking send button-ThrowExceptions

Exception or error:

I am developing a process which involves multiple forms. The idea is that whenever you click the send button of any form, after checking all the inputs have been filled, my js will hide the already completed form in order to show the new one.

The issue is that whenever I click send, the request launches six times inserting the same data over and over. There is no loop involved in the code, so my guess is that this has something to do with this listener:

contactForm.addEventListener('submit', function(event) {

located here:

var validation = Array.prototype.filter.call(contactForm, function(form) {
      contactForm.addEventListener('submit', function(event) {
        if (contactForm.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }

I am not sure however, since I’ve later tried to make some changes to no avail.

In any case, this is the code I started with:

(function() {
  'use strict';
  window.addEventListener('load', function() {
    var contactForm = document.getElementById('contactForm');
    var customerForm = document.getElementById('customerForm');

    var validation = Array.prototype.filter.call(contactForm, function(form) {
      contactForm.addEventListener('submit', function(event) {
        if (contactForm.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        contactForm.classList.add('was-validated');

        if (contactForm.checkValidity() === true) {
            customerForm.style.display = 'block';
            contactForm.style.display = 'none';
            event.preventDefault();
            (function() {
                var contactEmail = document.getElementById('contactEmail').value;
                var contactResellerId = 2;
                var contactName = document.getElementById('contactName').value;
                var contactLastName = document.getElementById('contactLastName').value;
                var contactCompany =  document.getElementById('contactCompany').value;
                var contactRegNum = document.getElementById('contactRegNum').value;

                $.ajax({
                    url: url,
                    method: 'POST',
                    crossDomain: true,
                    withCredentials: true,
                    data: JSON.stringify({
                        firstname: contactName,
                        lastname: contactLastName,
                        company: contactCompany,
                        email: contactEmail,
                        reseller_id: contactResellerId,
                        comregnum: contactRegNum
                    }),
                    dataType: 'json',
                    contentType: 'application/json',
                    headers: {
                        'Authorization': 'Basic '+token,
                    }
                })
                .done(function (response) { alert('Se ha creado el contacto!'); })
                .fail(function (jqXHR, textStatus, errorThrown) { alert(jqXHR); });
            })();
        }
      }, false);
    });
  }, false);
})();

And this is what I have right now:

(function() {
  'use strict';
  window.addEventListener('load', function() {
    var contactForm = document.getElementById('contactForm');
    var customerForm = document.getElementById('customerForm');
    var submitContact = document.getElementById('submitContact');

    var validation = Array.prototype.filter.call(contactForm, function(form) {
      submitContact.addEventListener('click', function(event) {
        if (contactForm.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        contactForm.classList.add('was-validated');

        if (contactForm.checkValidity() === true) {
                event.preventDefault();
                customerForm.style.display = 'block';
                contactForm.style.display = 'none';
                (function() {
                        var contactEmail = document.getElementById('contactEmail').value;
                        var contactResellerId = 2;
                        var contactName = document.getElementById('contactName').value;
                        var contactLastName = document.getElementById('contactLastName').value;
                        var contactCompany =  document.getElementById('contactCompany').value;
                        var contactRegNum = document.getElementById('contactRegNum').value;

                        $.ajax({
                                url: url,
                                method: 'POST',
                                crossDomain: true,
                                withCredentials: true,
                                data: JSON.stringify({
                                        firstname: contactName,
                                        lastname: contactLastName,
                                        company: contactCompany,
                                        email: contactEmail,
                                        reseller_id: contactResellerId,
                                        comregnum: contactRegNum
                                }),
                                dataType: 'json',
                                contentType: 'application/json',
                                headers: {
                                        'Authorization': 'Basic '+token,
                                }
                        })
                        .done(function (response) { alert('Se ha creado el contacto!'); })
                        .fail(function (jqXHR, textStatus, errorThrown) { console.log(jqXHR); });
                })();
        }
      }, false);
    });
  }, false);
})();

This is the form this is getting the info from:

<form class="needs-validation provisioningForm" id="contactForm" novalidate>
        <h2 class="title">Crear Contacto</h2>
        <div class="form-row">
            <div class="col-md-12 mb-3">
              <label for="contactName">Nombre</label>
              <input type="text" class="form-control" id="contactName" required>
              <div class="invalid-feedback">
                Debes introducir el nombre del contacto.
              </div>
            </div>
            <div class="col-md-12 mb-3">
              <label for="contactLastName">Apellidos</label>
              <input type="text" class="form-control" id="contactLastName" required>
              <div class="invalid-feedback">
                Debes introducir los apellidos del contacto.
              </div>
            </div>
        </div>

        <div class="form-row">
            <div class="col-md-12 mb-4">
              <label for="contactEmail">Email</label>
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text" id="inputGroupPrepend">@</span>
                </div>
                <input type="text" class="form-control" id="contactEmail" aria-describedby="inputGroupPrepend" required>
                <div class="invalid-feedback">
                  Debes introducir un correo vĂ¡lido.
                </div>
              </div>
            </div>

            <div class="col-md-12 mb-3">
              <label for="contactCompany">Empresa</label>
              <input type="text" class="form-control" id="contactCompany" required>
              <div class="invalid-feedback">
                Debes introducir el nombre de la empresa.
              </div>
            </div>
            <div class="col-md-12 mb-3">
              <label for="contactRegNum">C.I.F.</label>
              <input type="text" class="form-control" id="contactRegNum" required>
              <div class="invalid-feedback">
                Debes incluir el CIF de la empresa.
              </div>
            </div>
        </div>
        <button id="submitContact" class="btn btn-success" type="submit">Enviar</button>
    </form>

A few notes:

  1. Everything is working fine. There are no warnings/errors displayed on console. The issue lies in the fact that the POST request is executing 6 times.

  2. There are 5 forms with 5 submit buttons and a total of 5 functions. All have different id’s. As I was saying in the beginning, I believe the cause to be the event listener placed on the 'submit'. I think that since the other forms are just hidden, but there, it may be taking the other submits. But after trying to store them in separate variables and to place a .click listener on them and still get the same result I am even more confused.

If you need any extra info I’ll post it right away. Thank you all for your time and help.

How to solve:

It looks like you may be adding multiple “submit” events as you surmised. This line appears to be unnecessary:

var validation = Array.prototype.filter.call(contactForm, function(form) {

If you remove it (and the closing }), your submit event should be added only once, on window.load.

Leave a Reply

Your email address will not be published. Required fields are marked *