Double Ajax calls being made in Laravel application

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

Answer №1

There could be a case where your code is triggering two requests because of the usage of jQuery's 'one' method in this line:

$('.add-card').one('click',function(e) {
. This method binds the event handler to run only once for each selected element, so if there are multiple .add-card buttons on the page, it will create an event handler for each one.

An alternative approach would be to handle the form submission event instead. By preventing the default action with e.preventDefault(); and then getting the form data to make an AJAX call, you can avoid double requests.

If you choose not to go down that route, you could experiment with using .on() instead of .one(), like so:

$('.add-card').on('click', function(e) {
. However, I cannot guarantee that this will resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the uploaded images from uploadify on the webpage

I am currently working on a PHP website that utilizes uploadify for users to upload portfolio images. While I have successfully implemented uploadify, I am now exploring the most effective way to display these uploaded images on the webpage without requir ...

Using JavaScript, delete a class from an element

I am looking for a way to remove a specific class attribute from all elements on a webpage. The challenge is that I only have the class name as a reference, and cannot use any other identifiers like id or another class. Additionally, I cannot rely on JavaS ...

The element vanishes from sight after being detached and re-appended

Currently, I am utilizing hQuery's draggable and droppable features. My goal is to move an element from its original parent to its new dropped parent after dragging it. However, when I detach and append the element, it seems to disappear! What could ...

Leverage the power of JSON data in conjunction with HighCharts through

I'm struggling to understand the JSON format and HighCharts. Despite trying various techniques found on forums, I haven't been able to achieve the desired result. Here's my issue: 1- When clicking, an Ajax call is made to a PHP file that g ...

What is the best way to showcase search outcomes using ajax in a Django project?

In my current Django project, I am developing a feature that allows users to search for a name using a form. The view will then search for that name in the database after some transformation and display the results below the form. Currently, the entire pa ...

How to surround values and keys with double quotes using regular expressions in JavaScript

I am in need of a valid JSON format to request ES. I currently have a string that looks like this: { time: { from:now-60d, mode:quick, to:now } } However, when I attempt to use JSON.parse, I encounter an error because my ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

Comparing jQuery's min-width and width properties: A guide on eliminating pixels

Exploring some basic jQuery and JavaScript here. When I use the .width() method, I get an integer value. However, when I use .css('min-width'), it returns a value in pixels which makes it challenging to perform calculations. What would be the be ...

Dealing with JavaScript errors within an Express application

Consider the following async function export async function fetchData() { const result = await fetchData(); return result[0].id; } In the route, there is router.post( '/some-route', handleAsyncError(async (req: Request, resp: Response, _ ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...

Tips for creating brief animations

I am currently working with a moving div in JavaScript that continues to move for a period of time after the key is released. I am looking for a way to immediately stop the animation upon releasing the key. The animation is controlled by a switch statemen ...

Is it recommended to create model classes in React components?

Within the realms of React, the Flux architecture is utilized. According to https://reactjs.org/docs/thinking-in-react.html, React operates with two distinct models - namely, the state and props. There are recommendations provided for model management in ...

Is it possible to repeatedly activate a function using onmousedown just like with onkeydown?

My goal is to have the onmousedown event trigger repeatedly when the left mouse button is held down, instead of just once upon clicking. Currently, it only fires a single time. wHandle.onmousedown = function (event) { console.log('mouse b ...

Why does my script seem to be missing from this GET request?

Encountering an issue while setting up a page using npm and grunt. Request URL:http://localhost:9997/bower_components/requirejs/require.js Request Method:GET Status Code:404 Not Found The problematic html code is as follows: <script> ...

Prevent the resizing of my website on iOS devices using HTML and CSS

I'm encountering an issue with a website I developed that seems to be resizable on certain iOS devices, including the new iPhone X. I haven't been able to replicate this behavior on other standard websites. Perhaps there's a simple CSS solut ...

the click event fails to trigger when the id or class is modified

Hey there, I'm new to working with jquery and I've encountered a problem. Here's the code snippet: http://jsfiddle.net/8guzD/ $('#test.off').click(function(){ $(this).removeClass('off').addClass('on'); }) ...

What could be causing the mail() function to send an email with the body content set as "0"?

This content is being transmitted through Ajax. Here's the JavaScript code: $.ajax({ url: objCommon.ajax, type: 'POST', data: {type:'feedback', msg:$('.commonsFeedbackDiv').text(), url:window.location.href}, ...

PHP isn't getting the AJAX POST data from the JavaScript file

I've been stuck on this issue for hours now, unable to find a solution. Here is the javascript code snippet: function sendMovement(cel) { var name = "test"; $.ajax({ type: 'POST', url: '../game.php', ...

disable the form submission function in dropzone when buttons are clicked

Dropzone is being utilized on my page in the following manner alongside other input types such as text and select dropdowns: <form name="somename" method="post" action="/gotoURL" form="role"> // Other form elements here <div id="dropare ...

Erroneous deletion issue in React list causing removal of incorrect item

While working on creating a todo list in React, I faced an issue when trying to implement a delete function. The problem arose when attempting to delete an item - instead of removing the selected item, React ended up deleting everything except that specif ...