I am working on a Laravel application for managing tasks. The application has a form with four fields: one for the CSRF token, two hidden fields for IDs, and an input field to capture the task title.
For submitting the form, I have implemented AJAX. However, I am facing an issue where each AJAX request is being sent twice. This double submission problem occurs consistently across all AJAX requests in the application.
Below is a simplified version of my code:
JS
$(()=> {
$('.add-card').one('click',function(e) {
e.preventDefault();
var form = $(this).closest('form')[0];
let url = baseUrl + ":8000/api/task/store"
let data = retrieveFormData(form)
let _token = data['csrf-token']
ajaxCRUD("POST", url, {...data},_token, (response) => {
console.log(response);
});
});
});
function ajaxCRUD(method, url, data, token,successFunc) {
$.ajax({
type: method,
url: url,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', token);
},
success: function (response) {
if (successFunc) {
successFunc(response);
}
},
error: function (xhr, status, error) {
console.error(xhr.responseText);
},
});
}
function retrieveFormData(form) {
let formElements = $(form).find('input, select, textarea');
let formData = {};
formElements.each((index, element) => {
let name = $(element).attr('name');
let value = $(element).val();
formData[name] = value;
});
return formData;
}
HTML:
<div class="card fit-content px-1 py-2 position-absolute top-0 left-0 card-title-form" >
<form action="" method="post" class="task-title-form">
<input type="number" name="stage_id" class="form-control" value="{{$stage->id}}" hidden>
<input type="number" name="project_id" class="form-control" value="{{$project->id}}" hidden>
<input type="text" name="csrf-token" class="form-control" value="{{csrf_token()}}" hidden>
<input type="text" name="task_title" class="form-control" id="card-title" placeholder="Enter a title for this card...">
<div class="my-2">
<button class="btn btn-primary add-card" >Add</button>
<span class="btn font-14 close-title-form"><ion-icon name="close-outline"></ion-icon></span>
</div>
</form>
</div>
Solutions attempted without success:
verified if there are multiple event listeners on the element
changed <span> to <button>
attempted $(elem).one('click')
invoked by ID