JavaScript - Unable to get Ajax to function properly after div creation

I am facing an issue with my form button. Whenever I click the button, the form is generated but it doesn't work with Ajax after creation. Below are my script codes. The #testform seems to be correct as it works without creating the form. Any suggestions on how to fix this?

function addDiv() {
  var panel = document.querySelector(".add_new");
  var div = document.createElement("div");
  div.innerHTML = '<br> <form id="testform" method="POST">  <div class="row" style="padding-left:10rem;">  <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div>   <div class="col-md-2 text-left">  <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button>  </div>  </row> </form> <br>';
  panel.appendChild(div);
}

$("#testform").submit(function(e) {
  e.preventDefault();
  var formData = new FormData($("#testform").get(0));
  $.ajax({
    url: 'config.php',
    type: 'POST',
    data: formData,
    contentType: false,
    processData: false,
    success: function() {
      setTimeout(
        function() {
          $(".addToDatabase").html("Successfully.");
        }, 1000);
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>

<div class="add_new"></div>

Answer №1

Due to the order in which the second statement is executed, the submit event is not being listened to on the newly created <form>

function addDiv() {
   /*...*/
  panel.appendChild(div);
  $("#testform").submit(function(e) { /*...*/ });
}

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

Uploading images using the Drag and Drop feature in HTML

Hello, I'm having an issue with the drag and drop functionality. I want to expand the size of the input to cover the entire parent div, but for some reason, the input is appearing below the drag and drop div. Can anyone assist me with this? https://i. ...

Production environment does not support Meteor environment variables

I am currently deploying my app using Meteor UP and I have set the environment variables in both the mup.json file and a file called server/lib/env.js where they are stored. Here is how the variables are being accessed: Meteor.startup(function() { // ...

Tips for extracting a targeted array from a collection of arrays

When using array.some, I am having trouble getting a single array as an output. I attempted the following code: data = [{ Surname: 'Santos', Firstname: 'Carlos' }, { Surname: 'Reyes', Firstname: 'C ...

The Markdown-to-jsx tool is having trouble processing the provided source code

Utilizing a Material UI blog post template found at https://github.com/mui-org/material-ui/tree/master/docs/src/pages/getting-started/templates/blog, I have created my React app using npx create-react-app. Upon console logging the source, it displays as a ...

What methods can be used to focus on either an array or a string using user input, and then display its corresponding index?

What is the most effective method to determine a match between user input and an array or string, capturing the letter and its index within the data? For instance (sample scenario): GUESS THIS MOVIE: how to train your dragon ___ __ _____ ____ ______ T ...

What causes the Error: ENOENT open error to occur when attempting to render a doT.js view?

My first experience with doT.js led me to create a basic server setup: 'use strict'; var express = require('express'); var app = express(); var doT = require('express-dot'); var pub = __dirname+'/public'; var vws ...

Navigate back to the previous page following the completion of an AJAX data submission

When using ajax to send data from page A to the server, the spring controller returns welcome page B. This process works correctly on Firefox and Internet Explorer, but on Chrome, there is an issue where after successfully sending the data via ajax, the de ...

Teaching you the best way to incorporate numeral.js from app.locals into the script section of my jade file

Encountering issues while trying to utilize numeral.js within the script section of my jade file. Here is how I have numeral placed in locals: app.locals.numeral = require('numeral'); However, when I attempt to use numeral on a variable in my ...

Update a Firestore field if there have been no changes for 5 minutes

I am currently displaying cards that contain data from Google Firestore. One of the fields in these cards is "Status", which can be remotely turned on and off from outside the app. I want the Status to automatically switch to "Off" after 5 minutes or if th ...

Could variable scope change during asynchronous jQuery AJAX calls?

I am currently working on a system to track item stock, but I seem to be encountering an issue with the correct updating of statuses. In my JS code, it seems that the values of objects within the $.each loop are what is being utilized for operations like ...

Is there a way to reverse the JSON.stringify method?

I need help with decoding a string that contains arrays and JS objects which were originally converted using JSON.stringify function. Can someone guide me on how to accomplish this? Thank you for your assistance. ...

What is the most effective method for sharing features while maintaining unique aesthetics?

In the process of developing a Next.js website, I've encountered a challenge: I have 3 forms that function in similar ways but have different styles. Instead of duplicating code for each form, I'm looking for a way to build the form structure on ...

Ways to identify the specific button that has been clicked

I'm currently using Wordpress for my blog posts. All the posts are displayed on the same page with each post having a corresponding button. I need a way to identify which button belongs to which post when clicked. So far, I've only been successf ...

Utilize the power of Await Async while iterating through a massive JSON dataset

The data in the JSON file is quite extensive, weighing around 20MB. My goal is to ensure that the age returned is accurate, whether by waiting for the result or looping through the entire file. Currently, the output is always 0 even when the actual age is ...

What is the best way to transmit a Blob object to the server without it arriving empty?

I'm currently facing an issue where I am attempting to send a Blob object containing video data to my server for upload to my S3 storage. However, the Blob is arriving as an empty object on the server side. const blob = new Blob(videoChunks, { t ...

Choosing between global and local Node packages can be a crucial decision that affects

Recently, I discovered that Angular 2 is installed globally on my system, but I can't remember when I did that or if it's the recommended setup. It seems redundant since Angular can be defined in each project individually. This situation has me ...

Choose various div elements and modify their background colors

I have a PHP loop where I am creating multiple divs dynamically. Here is the code snippet: <?php for ($i=0; $i<=9; $i++) { for ($j=0; $j<=9; $j++) { echo "<div class=\"bg\" id=\"aaa".$i."&bsol ...

Using a function as a variable within jQuery's .click() method

Currently, I am utilizing a tabbed interface that is being managed by a jQuery function to handle the click events of my tabs. $(document).ready(function () { $('a#foo').click(function() { //content, various calls return fal ...

Using Jquery to toggle between display:none and display:inline-block

How can I change an element's display property from none to inline-block when clicking on another element? jQuery always reads the display: none setting. (function ($) { $(document).ready(function() { $("#click").click(func ...

Updating the content of a list item on the fly using React

After spending all day on this, I am feeling a bit frazzled. Trying to achieve what would take 20 seconds in JQuery has proven to be quite the challenge in React ¯\_(ツ)_/¯ In my application, tags are ranked by importance from 1 to 9. Simple enoug ...