1

When I execute the code I keep getting this error:

Uncaught TypeError: Illegal invocation

How do I fix this?

const formdata = new FormData();
for (const file of myfile.files) {
  formdata.append("myFiles[]", file);
}

$.ajax({
  url: '/all_backend_stuff/server.php',
  type: 'POST',
  data: {
    "file": formdata
  },
  success: function(response) {
    alert(response);
  },
  complete: function() {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="file" id="myfile" name="myFiles[]" accept=".pdf,.jpg,.png">
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Does this answer your question? [JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements](https://stackoverflow.com/questions/11071100/jquery-uncaught-typeerror-illegal-invocation-at-ajax-request-several-eleme) – Simone Rossaini Mar 10 '22 at 10:42
  • @SimoneRossaini not quite - that's a different issue – Rory McCrossan Mar 10 '22 at 10:50

1 Answers1

0

When sending FormData in a jQuery AJAX request you need to supply the object directly to the data property (not as the value of a property within an object).

In addition you need to set both contentType and processData to false:

$.ajax({
  url: '/all_backend_stuff/server.php',
  type: 'POST',
  data: formdata,
  contentType: false,
  processData: false,
  success: function(response) {
    alert(response);
  },
  complete: function() {}
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339