Sray
Sray

Reputation: 25

Multiple file upload via ajax, uploading file multiple times

Problem: File uploading works well when my page is loaded for the first time, but when I click on submit to upload another file the second time (with out reloading the page), the uploading is repeated twice. Generally, the uploading process is repeated as the number of subsequent steps(once for the first time, twice for the second time, and so on). I don't know why it is repeating the code over and over again. Please help. Thanks.

Here are my javascript and html files.

function upload() {
  $('#myForm').submit(function(e) {
    $.ajax({
      url: '/website/index.php/library_controller/upload',
      type: 'POST',
      data: new FormData(this),
      processData: false,
      contentType: false,
      success: function(result) {
        alert(result);
        var form = document.getElementById("myForm");
        form.reset();
      }
    });
    e.preventDefault();
  });
}
<form id="myForm">
  <input id="inputFile" name="userfile[]" size="20" multiple="true" type="file" value="Browse" class="btn btn-primary" style="display:inline;margin:10px"></input>
  <button class="btn btn-primary" onClick="upload()">Upload a new non-image file</button>
</form>

Upvotes: 1

Views: 1259

Answers (1)

Musa
Musa

Reputation: 97672

The problem is that you're binding a submit handler every time the submit button is clicked, you have to only bind it once, doing it at document ready is a good place. And you can remove the click handler.

$(document).ready(function(){
  $('#myForm').submit(function(e) {
    $.ajax({
      url: '/website/index.php/library_controller/upload',
      type: 'POST',
      data: new FormData(this),
      processData: false,
      contentType: false,
      success: function(result) {
        alert(result);
        var form = document.getElementById("myForm");
        form.reset();
      }
    });
    e.preventDefault();
  });
}

...

<form id="myForm">
  <input id="inputFile" name="userfile[]" size="20" multiple="true" type="file" value="Browse" class="btn btn-primary" style="display:inline;margin:10px"></input>
  <button class="btn btn-primary">Upload a new non-image file</button>
</form>

Upvotes: 1

Related Questions