Creating numerous AJAX scripts to handle dynamically created elements using JavaScript

In my coding script, I have a mechanism that dynamically creates form elements along with their unique IDs. For example,

If the response from the MySQL database is 4, then

<form ID="form0">
<Input>....
<Button type="submit>....
</form>

<form ID="form1">
<Input>....
<Button type="submit>....
</form>

<form ID="form2">
<Input>....
<Button type="submit>....
</form>

<form ID="form3">
<Input>....
<Button type="submit>....
</form>

After generating this list of forms, I use AJAX code to identify the submit buttons and send the input values to the database via a PHP page, like demonstrated below:

$(document.body).on('submit', '#form' ,function(e){
e.preventDefault();
var postData = $("#form").serialize();

$.post("../../../functions/processing.php",postData,function(data, status){
  var selectedData = JSON.parse(data);     
  $.each( selectedData, function( i, val ) {
             // perform specific tasks here...                                           
       });
});
});

My quandary is how to create multiple instances of this AJAX code for each dynamically generated form (form0, form1, form2, form3, etc.), since the number of forms generated is unpredictable. Is there a method to dynamically generate AJAX codes for dynamically created multiple forms?

Answer №1

Identify the form with a class that signifies it as a form to be managed by your AJAX handler. Then, in the handler, use this to access the form element being submitted.

<form ID="form0" class="js-ajax-form">
   <input>....
   <button type="submit>....
</form>

AJAX Handler

$(document).on('submit', '.js-ajax-form' ,function(e){

    e.preventDefault();
    var postData = $(this).serialize();

    $.post("../../../functions/processing.php",postData,function(data, status){
      var selectedData = JSON.parse(data);     
      $.each( selectedData, function( i, val ) {
                 // perform actions here...                                           
           });
    });

});

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

Automatically send a form with Ajax when the page is loaded

I have a form that needs to be automatically submitted when the page loads. Here is my current jQuery code: <script> // wait for the DOM to be loaded $(document).ready(function() { document.getElementById('form1').submit( ...

Exploring the variable scope in Node.js with a focus on separating routes

My routing configurations are stored in an external folder. Find them in the ./routes directory This is how I set up my routes within the server.js file: app.get('/', routes.index); app.post('/validation', register.valid); The reg ...

Tips for Rearranging Columns in an Array of Objects

I have an array of objects that I need to rearrange the columns and add a static value to each one: var homes = [ { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...

When context.getImgData() is invoked, it triggers a noticeable flickering effect on the canvas

Currently, I am integrating a webcam feed into a video element and then projecting it onto a canvas element. Subsequently, I am implementing face detection on the canvas to highlight faces with a square. The issue at hand arises when I call the context.ge ...

Issues with Fetch API and CORS in Web Browsers

Hello, I'm encountering an issue related to CORS and the Fetch API when using browsers. Currently, my setup involves running a NodeJS server built with Express on localhost:5000. This server responds to a GET request made to the URL /get_a, serving ...

Adjusting the Image Width in React to Match Bootstrap Column Width

Exploring the capabilities of the react-image-mapper library, I stumbled upon an interesting feature: the ImageMapper component offers a prop called width, representing the image width in pixels. Integrating this component into my application based on the ...

What is the best approach for utilizing Routes in place of Switch?

Recently, I've been diving into the world of routing, following a tutorial but I'm encountering some issues. The tutorial I am referring to is this one (26:45 - 29:00): https://www.youtube.com/watch?v=ntYXj9W1Ez8&t=1720s In my file, I have: ...

Error message thrown by a React custom hook: "Error: Queue is missing. This is probably a bug within React. Please report this issue."

In my React component, I need to utilize a custom React hook within the component. However, this hook should only be invoked when a specific feature toggle is enabled. I am aware that this approach may go against the rule of hooks as outlined here: https:/ ...

Include multiple connections between two points in an amCharts force-directed network

I'm currently utilizing the amcharts force directed network to display a knowledge graph. Within this knowledge graph, it's possible for two nodes to have multiple edges in both directions. For instance: A "person" could be linked as "born in" ...

Customize the Material UI InputBase component using date and time pickers styling

I have been working on customizing a date time picker option in material ui. After creating a styled Input that I liked, I attempted to use it as a base for my design. When I added the type="datetime-local" prop to the component, it provided the ...

Are variables initialized before the execution of ajax?

After reviewing the code snippet provided below, can we confirm with certainty that the id variable passed in the ajax call will consistently be assigned a value of 1? Or is there a possibility that the id could potentially be null or undefined at some p ...

Understanding the moment when the DOM is fully rendered within a controller

I'm currently facing an issue with AngularJS. In my controller, I have a $watch setup like this: function MyController() { $watch('myModel', function() { $rootScope.$emit('do-oper'); }); } The value of 'myMod ...

Elements animated using intersection observer are inconsistently functioning on the current page

My current challenge involves animating elements with the intersection observer, but I am encountering strange behavior with elements that are already on the screen when the page loads. These elements sometimes animate correctly and other times they do no ...

Is it true that .done function cannot be used in an ajax callback?

After adding .done to my ajax callback, I am encountering the following issue: Error: Object doesn't support this property or method This error is being displayed in the file myPage.aspx: function myFunction(albumNb) { alert("START myFun ...

Having difficulties implementing horizontal scrolling for the Tabs component in Material UI

I can't seem to enable horizontal scrolling for the Tabs in material UI. Here is the version of Material UI I am using: As the number of Tabs increases, they are becoming wider. I tried to set the width, but it ends up affecting the entire Tabs tab ...

"Exploring the various configurations for session handling in NodeJs

I am trying to implement a login system using the express-session module. I'm unsure if I have set everything up correctly, especially when it comes to the secret option. Currently, my initialization code for express-session looks like this: app.use( ...

Issue with Datatable filter dropdown display

I am currently working on implementing a filter dropdown for each column. While some columns are showing the unique values correctly, I am facing an issue with 3 columns where the dropdown is not displaying as expected. In these 3 columns, I have included ...

Attempting to establish an Observable in Angular 2/4 by subscribing to a JavaScript array object

I have a Service file where I am attempting to set as an observable, with a component that I would like to subscribe to it. Unfortunately, it doesn't seem to be working as expected. Can you please help me figure out what I am doing wrong? Service: Tr ...

In JavaScript, a true statement does not trigger a redirect

<label>Username:</label> <input name="username" id="username" type="text" value="testuser"> <label>Password:</label> <input name="password" id="password" type="password" value="test123"> <input value="Submit" name="su ...