3

I am trying to upload a file to my server using AJAX. The AJAX call works fine and my PHP returns correctly but when I add contentType: false and processData: false it no longer does.

var formData = new FormData();
formData.append('image', input.files[0]);

$.ajax({
    url: "php/API.php",
    data: {action: "changeProfilePicture", profilePicture: formData},
    type: "POST",
    contentType: false, // if i remove this
    processData: false, // and this, and my form data in `data:` then POST is not empty
    success: function(resp) {
        console.log(resp)
    }
});

// inside of php/API.php
<?php
    // post is empty
    print_r($_POST);

    if(isset($_POST) && !empty($_POST)) {
        ...
    }
?>
pats47
  • 133
  • 1
  • 4
  • 1
    well, contentType descripes the data send to your API and processData sets if and how data should be processed according to contentType. So contentType should not be false. – wayneOS Apr 05 '18 at 19:52
  • POST is still empty after removing `contentType`. – pats47 Apr 05 '18 at 19:54
  • Possible duplicate of [Sending multipart/formdata with jQuery.ajax](https://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax) – Oluwafemi Sule Apr 05 '18 at 19:56

1 Answers1

3

When sending multipart/formdata with jQuery.ajax, the request data should be an instance of FormData. e.g.

var formData = new FormData();
formData.append('image', input.files[0]);
formData.append('action', 'changeProfilePicture');
$.ajax({
    url: "php/API.php",
    data: formData,
    type: "POST",
    contentType: false, 
    processData: false,
    ...
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81