Using JQuery to create a button inside a Modal dialog box

My goal is to select a row within a Table that is located inside a Modal window, and then have a button ('newBtn') within that Modal window trigger a post request to the server with the selected id of the row. However, the issue I am encountering is that when the button is pressed, it sends multiple posts corresponding to every previous click on a row, instead of just sending one post with the selection of the last clicked row. For example, if rows 1, 2, and 3 have been previously clicked, the button will send 3 posts rather than only sending the data from the most recent click on row 3.
I suspect that there may be an incorrect placement of brackets in the code, but moving the button outside of the modal function results in it not firing at all. Any assistance would be greatly appreciated.

var table = $('#example').DataTable();
    var tableBody = '#example tbody';
    var form = new FormData();

    $(document).ready(function() {

        $(tableBody).on('click', 'tr', function () {

            var cursor = table.row($(this)); // get the clicked row
            var selected_id = cursor.data()[0]; // this will provide the id in the current row.

            $('#myModal').on('shown.bs.modal', function (event) {
                $("#testbutton").trigger("click");
            });


            $("#newBtn").on("click",function(){
                form.set("selected_id", selected_id);

                var settings = {
                    "url": "http://127.0.0.1:5000/test",
                    "method": "POST",
                    "timeout": 0,
                    "processData": false,
                    "mimeType": "multipart/form-data",
                    "contentType": false,
                    "data": form
                };

                $.ajax(settings).done(function (response) {
                    console.log(response);
                });

            });

        });

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog" style="min-width: 1080px">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <div class="table-responsive">

          <table class="display" id="example" style="text-align: center; width: 100%">

            <thead>
              <tr>
                <th>id</th>
                <th>Date</th>
              </tr>
            </thead>

            <tbody>

              <tr>
                <td>1</td>
                <td>'2020-06-01'</td>
              </tr>
              <tr>
                <td>2</td>
                <td>'2020-06-02'</td>
              </tr>

            </tbody>
          </table>
        </div>

        <button type="button" id="newBtn" class="btn btn-sm btn-info">Send post</button>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

Answer №1

let data = $('#example').DataTable();
let body = '#example tbody';
let form = new FormData();

Integrate this code within

$(document).ready(function() { });  

And eliminate the following script

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №2

the content within the header tag is as follows:

<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>

Therefore, your recommendation is :

var table= $('#example').DataTable();
    var tableBody = '#example tbody';
    var form = new FormData();

    $(document).ready(function() { });

    $(tableBody).on('click', 'tr', function () {

        var cursor = table.row($(this));//get the clicked row
        var selected_id = cursor.data()[0];// this will give the id in the current row.

        $('#myModal').on('shown.bs.modal', function (event) {
            $("#testbutton").trigger("click");
        });


        $("#newBtn").on("click",function(){
            form.set("action", "select_id");
            form.set("selected_id", selected_id);

            var settings = {
                "url": "http://127.0.0.1:5000/test",
                "method": "POST",
                "timeout": 0,
                "processData": false,
                "mimeType": "multipart/form-data",
                "contentType": false,
                "data": form
            };

            $.ajax(settings).done(function (response) {
                console.log(response);
            });

        });

    });

Despite implementing these changes, the issue remains unresolved on my side: upon selecting row 1 and then row 2, the button triggers two posts instead of just one post with the data from row 2.

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

Ensuring that $.each properly processes all deferreds in jQuery

I am currently working with the following jQuery code: myFunc: function(cmd, obj){ var idToExtMap = this.map; var requireRes = this.reqInst; var deferreds = []; var ret = true; $.each(idToExtMap[cmd], function( ...

Wait until the user submits the form before activating Angular validations, and do not display any validation messages if the user deletes text from a text box

I am looking to implement angular validations that are only triggered after the user clicks on submit. I want the validations to remain hidden if the user removes text from a textbox after submitting it. Here is what I need: - Validations should not be dis ...

Getting the length of child elements in Angular using ngFor loop

Can anyone help me figure out how to check the length of a child element in my Angular *ngFor loop? I am fetching data from a real-time firebase database. What am I doing wrong? Here is the code snippet I am using: <div *ngFor="let event of events"> ...

Populate a PHP array with designated file types from a designated folder, to later be loaded into a JavaScript array

My goal is to populate a JavaScript array with files of type .dae from different directories: "/collada/basement", "/collada/ground", "/collada/first", and "/collada/roof". I'm thinking of creating separate arrays for each directory. I understand that ...

retrieving embedded content from an iframe on Internet Explorer version 7

Need help with iframe content retrieval $('.theiframe').load(function(){ var content = $(this.contentDocument).find('pre').html(); } I'm facing an issue where the iframe content is retrieved properly in FF, Chrome, and IE 8,9 ...

The requested resource at http://js:port/socket.io/1/ could not be located (Error 404

Having trouble connecting with Socket.io. This is the server-side code: function chatserver(){ var express = require('express'), app = express(), server = require('http').createServer(app).listen(app.get('port'),function ...

What's preventing me from invoking this object's function through an inline anchor?

CSS: <div class="box"> <p>This is a box</p> </div> Javascript: var box = { content : (function() {return ("This is the content of the box")}) }; alert("Box content: \n" + box.content()); $("output").text( +"<br/ ...

Is the variable not being initialized outside of the function?

I'm really struggling with this async issue. I can't seem to get it to work because the summonerData array is not being set. I have a feeling it has something to do with async, but I'm not sure how to troubleshoot it. var summonerName = req ...

React error: Updating state is only allowed on mounted or mounting components

I'm encountering this Error/Warning message in my console: The error message says: setState(...): Can only update a mounted or mounting component. Addressing the Component Mounting Process When it comes to mounting the component, here's the r ...

Encountering an error when attempting to access the 'path' property of undefined from a user-defined input file in Bootstrap 4

I'm currently working on a form that includes a custom input group for selecting a local image file. Unfortunately, I am having trouble retrieving the file name in my server code. Despite checking req.body and trying req.file.path, I have been unable ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...

Erase every picture contained within the element

<div id="uniqueidhere"> <span> <span><img src="image1link"></img></span> <span><img src="image2link"></img></span> <span><img src="image3link"></img></span> <span>&l ...

Dragging elements with jQueryUI multiple times

Is there a way to configure drag and drop functionality so that one element can be dragged multiple times? I attempted to create something similar to this http://jsfiddle.net/28SMv/3/, but after dragging an item from red to blue, the element loses its abi ...

Combining data from multiple API calls in a for loop with AngularJS

I'm working with an API that contains pages from 1 to 10 and my goal is to cycle through these page numbers to make the necessary API calls. app.factory('companies', ['$http', function($http) { var i; for (i = 1; i < 11 ...

Animating the background of an element to be null using jQuery

When hovering over an element with no background, I've implemented a hover effect that animates the background color. The animation works on hover, but does not revert back to no background when not hovered: $('#home_sensors_products').hove ...

Modifying browser.location.href Cancels AJAX Requests

I am facing an issue with my HTML page. I have a button that, when clicked by the user, updates the window.location.href to the URL of a text file. In order to ensure that the file is downloaded and not opened in the browser, the text file is served with C ...

Angular event not refreshing the data

Just starting out with Angular, I was advised against using jQuery alongside it. However, there are times when I find jQuery more convenient to use. Recently, I created a function to fetch a list of comments. function displayComments(){ app.co ...

Implementing inline styles in the HEAD section of a Next.js website

I currently have a blog hosted on Jekyll at , and I'm looking to migrate it to Next.js. My unique approach involves embedding all the styles directly into the HEAD element of each HTML page, without utilizing any external stylesheet files. However, wh ...

Reacting with Angulatory: Response heads are not being transferred in applications

I'm facing an issue where the cookie containing my authentication token doesn't get passed along with my requests. After authenticating in Chrome, the response sets the cookie correctly, but it's not included in subsequent requests. This is ...

Troubleshooting a problem with Angular routing when trying to access a specific URL using

My main objective is to enable users to view products by clicking on the item itself. For each product item displayed in main.html, the URL format is like this... <a href="/products/{{ product.id }}">{{ product.title }}</a> For instance, when ...