0

I can't figure out why the form redirects after being submitted. So, this is how my code works: When the mouse is entered (mouseenter) the button edit appears. When this button is clicked I send ajax request to the server, and I get as response a form with select options, so far so good. But, when I choose (select) something and hit update, the form redirects despite the fact that I wrote evt.preventDefault(), and subsequently ajax failed working. I got stuck and I can't figure out where the bug is. I appreciate any suggestions. Thanks in advance. Here is my code:

$('div.js-service-company').mouseenter(function(evt) {
  const thisDiv = $(this);
  const link = $(this).children().children('a');
  const p = $(this).children();
  let url = link.attr('href');
  let currentTicketState = url.substring(url.lastIndexOf('=') + 1);
  const ticketId = link.attr('data-id');

  if (allowedTicketStates.includes(currentTicketState)) {

    const btn = $('<button/>', {
      type: 'submit',
      name: 'serviceCompanyData',
      class: 'btn btn-success btn-sm btn-edit-service-company',
      text: 'Edit'
    });

    p.append(btn);

    $('button.btn-edit-service-company').click(function(btn) {
      btn.preventDefault();
      const thisBtn = $(this);

      $.ajax({
        type: "GET",
        url: '{{ path('
        admin_cms3_core_ticket_getServiceCompany ') }}',
        data: {
          ticketId: ticketId,
        },
        success: response => {
          link.parent('p').append(response);
          link.hide();
          thisBtn.hide();
          $('div.js-service-company').off("mouseenter");
        },
        error: (jqXHR, textStatus) => {
          console.log("Error occurred: " + textStatus)
        }
      });

    });
    // this is where the form submission occurres
    $('form#service-company-form').submit(function(evt2) {
      evt2.preventDefault();

      const form = $(this);
      const type = form.attr('method');
      const thisUrl = form.attr('action');

      $.ajax({
        type,
        url: thisUrl,
        data: form.serialize(),
        dataType: 'json',
        async: false,
        success: response => {
          $('body div').removeClass("loader_wrap loader_background");
          form.hide();
          link.text(response.serviceCompany);
          link.show();
        },
        error: err => {
          console.log(err)
        }
      });
    });
  }
}).mouseleave(function() {
  $('button.btn-edit-service-company').hide();
  const objectId = $(this).attr('data-id');
  $('.service_company-'.concat(`${objectId}`)).hide();
});
The html code:
<td class="sonata-ba-list-field sonata-ba-list-field-string" objectid="326966">

  <div class="js-service-company">
    <p>
      <a data-id="326966" href="/app_dev.php/cms3/core/company/6/show?state=closed1">Text_01</a>
    </p>
    Company Name
  </div>
</td>
mplungjan
  • 134,906
  • 25
  • 152
  • 209
Capfer
  • 459
  • 5
  • 15
  • I removed the first line of the snippet since it does not run – mplungjan Aug 27 '19 at 11:24
  • I do not understand why you do not just show/hide the button on hover instead of this overly complex set of event handlers you add and remove – mplungjan Aug 27 '19 at 11:27
  • There is so much wrong with the above code. Please post the HTML and perhaps we can fix it. For one, add the button in the HTML and hide it with CSS. Then you can toggle it with script instead of adding it on each mouseover – mplungjan Aug 27 '19 at 11:56
  • @mplungjan I have included the html code, please check. – Capfer Aug 27 '19 at 12:32
  • And how to test this? `if (allowedTicketStates.includes(currentTicketState)) {` – mplungjan Aug 27 '19 at 12:33
  • @mplungjan, here I'm just checking if the string is in the url like so: const allowedTicketStates = ["new", "planned", "completed", "pending", "approved"]; – Capfer Aug 27 '19 at 12:39
  • Your example is "closed1" – mplungjan Aug 27 '19 at 12:43
  • @mplungjan, I left it out by mistake. It's just a string like so "closed1". – Capfer Aug 27 '19 at 12:56
  • Here is what I meant https://jsfiddle.net/mplungjan/c9m26zhr/ - it is not complete but gives you an idea – mplungjan Aug 27 '19 at 13:18

1 Answers1

0

The event you got is selecting an element which is not present in DOM. After your ajax call you inject new markup to the dom. To bind your events to these elements you can use the .on method:

$(document).on('submit', 'form#service-company-form', function (evt2) {
    evt2.preventDefault();
    // ...
});

As mplungjan suggested is this syntax better

$('#service-company-form').on('submit', function (evt2) {
    evt2.preventDefault();
    // ...
});

because jQuery will not listen on every submits in document and filter for the selector. This will only fire when #service-company-form is submitted.

kmgt
  • 5,826
  • 4
  • 18
  • 41