0

I am trying to upload a file to my server using JQuery, AJAX and a PHP script to handle the server-side uploading. I've tested my PHP script, which is now fully functional. However, I'm facing some difficulties with my JQuery. After some testing I found that most likely the FormData is empty or isn't being send to the server.

My code looks like this:

HTML:

<form id="upload" enctype='multipart/form-data'>
    <input type="file" name="file" id="file" />
    <a href="#" id="upload-button" class="upload">
    <span class="upload-text">Upload</span>
    </a>
</form>

JQuery:

$(document).ready(function(){
    $("#upload-button").click(function(e) {
        document.getElementById("file").click();
        e.preventDefault();
    });

    $("#file").change(function(e) {
        e.preventDefault();
        $('.upload-text').html("Uploading...");
        $('#upload').submit();
    });

    $('#upload').submit(function(e) {
        e.preventDefault();
        //var fileData = $('#file').prop('files')[0];   
        //var formData = new FormData();                  
        //formData.append('file', fileData);

        var formData = $('#upload').serialize();

        $.ajax({
            url: 'ajaxupload.php',
            type: 'post',
            data: formData,
            contentType:false,
            processData:false,
            enctype: 'multipart/form-data',
            async: false,
            success: function(data){
                $('.upload-text').html(data);
            }
        });
    });
});

I have tried using the following, but that also isn't working:

var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);

As well as that, I've also tried using var formdata = new FormData(this); and placing new FormData(this); directly in the AJAX request. Lastly, I've also tried using params: instead of data:, sadly to no avail. My PHP script should return a link to where the file can be downloaded, which should then be displayed in the element with class upload-text.

I am using JQuery 3.3.1 (newest).

Reaper Music
  • 105
  • 1
  • 7
  • "_I found that most likely the FormData is empty or isn't being send to the server"_ - This can easily be determined by looking at the request in the developer tools (or any other proxy) – Andreas Jun 20 '18 at 16:42
  • jquery does not support file format in the ajax posting i believe – Avi Teller Jun 20 '18 at 16:44
  • You need to send binary file data in a `FormData` object. See the duplicate for more detailed information – Rory McCrossan Jun 20 '18 at 16:47
  • @Andreas Thanks for your comment. I've looked at the Network tab on the developer tools and it is posting to the PHP file, however, FormData is completely empty. – Reaper Music Jun 20 '18 at 16:47

0 Answers0