[Solved] How I Can send a file with Ajax?


You need to create a form data object. In the ajax function,
set processData to `false.

Because data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type “application/x-www-form-urlencoded”. If you want to send a DOMDocument, or other non-processed data, set this option to false.

JS

  $("form").submit(function(evt){    
      evt.preventDefault(); //prevent refresh
      const formData = new FormData(this); // you need to create a FormData obj to be able to send files
   $.ajax({
       url: 'upload-my-files', //change this to your url
       type: 'POST',
       data: formData, //put formData as body data
       cache: false,
       contentType: false,
       enctype: 'multipart/form-data',
       processData: false,
       success: function (data) {
         console.log(data);
       }
   });
 });

References:

https://developer.mozilla.org/en-US/docs/Web/API/FormData

http://api.jquery.com/jquery.ajax/

7

solved How I Can send a file with Ajax?