-3

My goal is to create a form to send an image to the server through Ajax via jQuery.

I already asked the question here (Problem sending a form with a jquery file component by ajax), but it's been closed and it still doesn't work. From my question, I changed the sending function like this (according to this post: jQuery AJAX file upload PHP):

$( "#sendProfileImg").on('submit', function(e) {
  e.preventDefault();
  var file_data = $('#profileImgFile').prop('files')[0];   
  var form_data = new FormData();                  
  form_data.append('file', file_data);
  console.log(form_data); 
  $.ajax({
    url: 'uploadImage.php',
    data: form_data,
    type: 'POST',
          dataType: 'text',
          contentType: false,
          cache: false,
          processData:false,
    success: function( data ) {
      console.log(data);
    }
  });
});

But the answer I get from my uploadImage.php file (which consist of just var_dump($_POST);) is the following:

array(0) {
}

Any advice?

halfer
  • 19,824
  • 17
  • 99
  • 186
csi_bern
  • 5
  • 6

3 Answers3

-1

Since your request only has the file you might want want to use the $_FILES variable instead of $_POST. Uploaded files can only accessed through the $_FILES variable.

-1

three things

  • use $_FILES instead $_POST please check this url

  • check if you have an updated browser(not all browsers are compatible with FormData) check the browser compatibility here

Emiliano
  • 698
  • 9
  • 30
-1

Thank you very much everbody, the problem is solved.

I discovered 2 issues:

  1. I have to use form_data.append. I didn't know this function and it wasn't on the tutorials I followed. Furthermore, I had to use this funtion for every field of the formular, not just the one with the file
  2. $_POST return no information about the posted files. That's why I didn't get any return about the posted information.

Thanks again everybody

csi_bern
  • 5
  • 6