Home > Enterprise >  JQuery won't fire an action from modal
JQuery won't fire an action from modal

Time:06-02

I have the following form in a Bootstrap modal window

            <form id="formCsv"  enctype="multipart/form-data">
              <div >
                <input  type="file" id="file" name="file">    
              </div>
                <div >
                <button type="submit" id="csvBtn" name="something"> Upload </button>
              </div>
              <div id="loading" >
                <div  role="status"></div>
              </div>
              <div >
                <button type="button" id="export-btn"  disabled>Export CSV</button>
              </div>
            </form>

JQuery file

console.log("Works");

$(document).ready( function() {
    // Submit form data via Ajax
    $("#formCsv").on('submit', function(e)
    {
        alert("test");
        e.preventDefault();
        var form_data = new FormData($(this)[0]); 

        $.ajax({
            type: 'POST',
            url: 'src/positionen/getCsvData.php',
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(response)
            {
                console.log(response);
                var json = JSON.parse(response);                
                addToTable(json);
            },
        });
    });
});

The console.log() works. The alert() within is not triggered and no errors are thrown.

Any ideas why it is like this?

Without the form in a modal it just works fine.

CodePudding user response:

I see the problem.

The form is loaded later into the DOM you need to change your listener to $(document).on('submit', '#formCsv', function() {//your code})

That way Jquery will also listen to content that is added later by an ajax call.

  • Related