skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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.

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search