AJAX failing to submit

I am working on a Laravel project where the admin has the ability to modify user data through a form. I am trying to implement an AJAX submission for this form, but it is not working as expected.

Here is the form code:

<form id="userData{{$loop->iteration}}" method="POST">
@csrf
<!--some inputs-->
</form>

<button id="changeUserData{{$loop->iteration}}" data-id="#userData{{$loop->iteration}}">Save</button>

And here is the JavaScript code:

$("#changeUserData{{$loop->iteration}}").click(function (e) {
  var ele = $(this);
  var formId = ele.attr("data-id");
  console.log(formId);
  $(formId).submit(function (e){
    console.log("test2");
    e.preventDefault();
    $.ajax({
      url: '{{url('changeUserData')}}',
      method: "PATCH",
      data: $(formId).serialize(),
      success: function(){
        console.log("test");
      }
    })
  })
});

Even though the first console log statement gets executed when the button is pressed, nothing else happens afterwards. I have verified that the formId matches the form id correctly, so I am unsure what could be causing the issue.

Answer №1

The issue lies with the .submit() function when used with the handler argument as it does not actually submit the form itself, but rather attaches an event handler to the form's submit event.

To resolve this, simply remove the binding and the functionality should work as intended:

$("#changeUserData{{$loop->iteration}}").click(function (e) {
    var ele = $(this);
    var formId = ele.attr("data-id");
    console.log(formId);

    $.ajax({
        url: '{{url('changeUserData')}}',
        method: "PATCH",
        data: $(formId).serialize(),
        success: function(){
          console.log("test");
        }
    })
})

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

Connect two radio buttons across separate forms

I am encountering an issue with two radio buttons that I am trying to link together. The problem arises because they are located in two separate form elements, causing them not to function as intended. It is important for the forms to be utilized in Bootst ...

Generate a fresh JSON object following a click event triggered by an HTTP PUT request

I have the following structure in JSON format: "disputes": [ { id: "", negotiation_type: "", history:{ user_flag: "", created_at: "", updated_at: "", created_by: null, updated_by: null, ...

Elevate to Babel 7: Unable to access the property 'bindings' of null

I recently made the switch to Babel 7 (upgrading from version 6) using the following commands: npm remove babel-cli npm install --save-dev @babel/cli @babel/core @babel/preset-env This is the content of my .babelrc file: { "presets": ["env"] } After th ...

React onClick event image attribute is unique because it allows for interactive

Is there a way to dynamically add the onClick attribute to an image, but have the click event not working? //Code const parser = new DOMParser(); const doc = parser.parseFromString(htmlContent, "text/html" ); const imageDa ...

Eliminate repeated elements within a JSON dataset to create a consolidated array

Looking to extract unique data from the JSON object below in order to create a result json with a list of questions and their corresponding choices. Any assistance would be greatly appreciated. Thanks in advance..!! var data = [ { "category": "s ...

Convert an AJAX JSON object into values for multiple text boxes

When making an ajax call, I receive the following JSON input: var json = { "id_u":"1", "nombre_usuario":"JESUS", "apellido_paterno_usuario":"DIAZ", } I have text inputs that correspond to each key in the JSON object: <input type="text" name="id ...

What is the proper method for overriding styles in material-ui v5 for properties that are not present in the themes components?

Currently, I am customizing MuiDataTables using the adaptv4theme in the following manner: declare module '@material-ui/core/styles/overrides' { export interface ComponentNameToClassKey { MUIDataTable: any; MUIDataTableFilterList: any; ...

The implementation of a universal translation system in Express JS

I have developed a straightforward translation module for Express JS. It exists as a global object in the application scope and is initialized during application runtime: translator.configure({ translations: 'translations.json' }); I have i ...

How to run .lnc files in Node.js

I encountered an issue while trying to open a shortcut (.lnk) file using node.js. What is the correct way to do this? var exec = require('child_process').execFile; var runLibreOffice =function(){ exec('D:\\Downloads\&b ...

What could be causing the mouseenter event listener to function properly on the initial grid-item but fail to work on the remaining items?

When I hover over any of the grid items, I want the addToCartBar to only show on that specific item. However, currently it is only working on the first item. What am I missing? Below is the relevant ejs code: <div class="main-cont"> ...

Could not locate the term 'group member'

I am currently working on developing a moderation bot using Discord.js v13. In order to implement functionalities such as mute, kick, warn, and ban commands, I need to verify user permissions. However, I am encountering an issue with my code where it fails ...

Building a custom tooltip for a Bootstrap multiselect dropdown menu

I have been attempting to implement a tooltip on a multiselect dropdown menu that I constructed using the Bootstrap-select jQuery plugin... Here is how I coded my select in the HTML... <select id="dropDownList" class="selectpicker" t ...

Angular 2/JS - Date expression functions exclusively in the Chrome browser

Today, I decided to test my app using my FireFox browser instead of Chrome like usual, and I was surprised to find that my app isn't functioning properly. After some investigation, I discovered that the code snippet below is causing the issue by disp ...

Assign the output of a function to a variable

I am trying to retrieve data from a function call in nodejs and assign it to a variable. The desired output should be "Calling From Glasgow to Euston", but I'm currently getting "Calling From undefined to undefined". Here is the code snippet: functi ...

Issue with EJS template displaying no information

I am encountering an issue with ejs templates. While I have successfully used it in a previous project, in my current one, it's not working as intended. Instead of rendering the cards with the passed data, all I see is a blank page. Here is my code fo ...

The error message "Unable to call mxgraph function during Jest unit testing" occurred during the execution of

My Vue JS Component is utilizing the mxgraph package, which can be found at: https://www.npmjs.com/package/mxgraph The component imports the package like so: import * as mxgraph from 'mxgraph'; const { mxClient, mxStackLayout, mxGraph, ...

Eliminate items from one array when there is a corresponding match in a separate array using JavaScript

I am working with 2 JavaScript arrays First Array var columns=[{name: 'id', default: true}, {name: 'type', default: true},{name: 'typeName', default: true}, {name: 'client', default: false}]; Second Array var unSel ...

Using the React Native framework to incorporate headers with the Linking API

Is there a way to setRequestHeader in React Native, similar to the example below: var client = new XMLHttpRequest(); client.open("GET", "http://www.example.com/api"); client.setRequestHeader("authorization", "Bearer Access_Token"); client.send(); I have ...

Deactivate AJAX Page Linking for jQuery Mobile within Wordpress

I have integrated jQM into my WordPress site, raigle.net, and now I need to disable AJAX functionality. The challenge is that jQM is loaded in functions.php. How can I achieve this? Here is the code I used to integrate jQM: function custom_theme_files() ...

Issue with state not being reflected accurately

I am attempting to retrieve images from my Firebase storage using the following code: const [images, setImages] = useState([]); useEffect(() => { function list() { const storage = getStorage(); const imagesRef = ref(storage, "tes ...