Pass files by ajax

1

I'm creating the product registration form for a website, and in it, all forms are submitted by ajax to an api. The problem is that in this particular form I need to send images to the server. I'm trying to use the FormData object for sending, but to no avail. Here's the javascript code I'm using:

$("#formProduto").submit((e) => {
    var formProduto = document.getElementById('formProduto');
    var formData = new FormData(formProduto);
    $.ajax("/admin/produto/api", {
        type: "POST",
        data: formData,
        success: (data) => {
            //Sucesso
        }
    }
    return e.preventDefault();
});

Using data: $("#formProduto").serialize() (without the file, of course) ajax works normally, when I change the code above it just ignores the e.preventDefault(); and submits the form to the page itself.

    
asked by anonymous 25.09.2017 / 01:57

1 answer

3

First check if your form has the enctype="multipart/form-data" attribute that allows you to upload files, then change your code to something like:

var fData = new FormData($('#formProduto')[0]);
$.ajax({
  url : "/admin/produto/api",
  dataType: 'json',
  processData: false,
  data: fData,
  type: 'POST',
  contentType: false,
  success : function() {
    console.log("success", success);        
  },
  complete: function() {
    console.log("complete", complete);
  },
  error: function() {
    console.log("error", error);        
  }
});

Adding the options processData: false and contentType: false

    
25.09.2017 / 02:07