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>