I have a simple Laravel application for task management. It includes a form with four fields: one for the CSRF token and two hidden fields for IDs, and one input field to get the task title.
To submit the form, I'm using AJAX. However, I'm encountering an issue where every AJAX request is sent twice. This behavior persists across all AJAX requests in the application.
Here's 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 tried with no luck:
checked if there are multiple event listeners on the element
changed <span> to <button>
tried $(elem).one('click')
called by ID
One reason why your code might be making two requests is because here
$('.add-card').one('click',function(e) {,you're using jQuery's 'one' method, which binds the event handler to execute once for the selected elements. If there are multiple .add-card buttons in your document, this might create an event handler for each element.One solution would be to use the 'submit' event on the form. When the form is submitted, you can prevent redirection by using
e.preventDefault();then retrieve the form data and make the AJAX request.If you do not wish to do that, you can try using .on() instead of .one(), like this:
$('.add-card').on('click', function(e) {However, I'm not sure if this will work, to be honest.