简体   繁体   中英

Form Submission not working second time after submiting using Jquery and Ajax

I have made a PHP page that submits data internally using AJAX and Jquery. It works fine, but after submit when I click on submit again(second time) it does not happen.. Here is the code for reference

$(function(){
    $('#sub').click(function(){
        $('#myForm').on('submit',function(e){
            e.preventDefault();
            $.ajax({
                url:"file.php",
                type:'POST',
                data:new FormData(this),
                contentType: false,
                processData:false,
                success:function(data){
                    $("#myResponse").replaceWith(data);}
                });
            });
        });
    });
});

This is the submit button inside from

<input type="submit" value="Submit" name="submit" id="sub" onclick="submitForm('file.php')" data-toggle="modal" data-target="#myModal">

Remove the (onclick="submitForm('file.php')") from the input type. And also remove "$('#sub').click(function(){});" . only keep it like:

  $('#myForm').on('submit',function(e){
   e.preventDefault();
   $.ajax({
   url:"file.php",
   type:'POST',
  data:new FormData(this),
  contentType: false,
  processData:false,
  success:function(data){
  $("#myResponse").replaceWith(data);}
    });
   });
  });

Remove the other click events, delegate your submit event

$('body').on('submit','#myForm', function(e) {
  e.preventDefault();
  $.ajax({
    url: "file.php",
    type: 'POST',
    data: new FormData(this),
    contentType: false,
    processData: false,
    success: function(data) {
      $("#myResponse").replaceWith(data);
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM