$_FILES returning empty

Asked

Viewed 185 times

0

This is the form I’m using to send the file

<form id="form_converter" enctype="multipart/form-data">
    <input type="file" name="arquivo" />
    <input type="submit" value="Enviar" />
</form>

$(document).on("submit", "#form_converter", function(){
    var dados  = $('#form_converter').serialize();
    jQuery.ajax({
        type: "POST",
        url: "sys/cv_unique_file.php",
        data: dados,
        success: function(data)
        {
            console.log(data);
        }
    }); 
    return false;
});

And in my PHP

if(isset($_FILES)){
    print_r($_FILES);
}

And I just get an empty array Array (), already check the permission of the folders and ta all 777

1 answer

0

the function serialize() does not include fields of type file in the generated "query string", suppose in your form you had 2 fields of the type text, thus the serialize() would generate a string similar to this.

<form action="">
   <input type="text" name="nome">
   <input type="text" name="telefone">
   <input type="file" name="arquivo">
   <input type="submit" value="Enviar">
</form>

$('form').on('submit', function(event) {
   event.preventDefault();

   console.log($(this).serialize());
});

// Resultado do console.log: nome=aew&telefone=aew

That one string generated by serialize() shall be sent via the ajax.

To send files using ajax you need to use the class FormData, in this way:

$('form').on('submit', function(event) {
   event.preventDefault();

   var formData = new FormData(this);

   $.ajax({
     type: "POST",
     url: "sys/cv_unique_file.php",
     data: formData,
     success: function(data) {
        console.log(data);
     }
   }); 
});
  • I didn’t know this about serialize(), but its function is returning the following error: Uncaught Typeerror: Illegal Invocation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.