How to work with filepond plugin, ajax and php, file name not detected on the server

Viewed 2086

I am trying to upload file to an xammp server. I'm unable to access the file it uploaded. I doubt on this link server: 'http://localhost/', because when I change it to the name of PHP file that process data on the server side it works.

But also I added another field called username on the form, look below on the code, and I want to combine them on single submit event with Ajax, but I have no idea for this combination.

  //initialize file pond with jquery plugin
  $('#file').filepond({
    allowMultiple: false,
    server: 'http://localhost/'
  });
  //ajax

$("form").on('submit', function(e) {
  $.ajax({
    url: 'send.php',
    type: 'POST',
    data: new FormData(this),
    dataType: 'JSON',
    contentType: false,
    cache: false,
    processData: false,
  }).done(function(data) {
    if (data.success == false) {
      if (data.errors.username) {
        $('#username').append('<span class="text-danger">' + data.errors.username + '</span>');
      }
      if (data.errors.file) {
        $('#file').append('<span class="text-danger">' + data.errors.file + '</span>');
      }
    }
  });
  
  e.preventDefault();
});

//my form field between form tag
<form method="POST" enctype="multipart/form-data"> 
   <input type="text" name="username" id="username">
   <input type="file" name="file" id="file">
</form>

//php code validate file and name
$errors = [];
if(empty($_FILES['username'])) {
    $errors['username'] = 'Enter your name!';
}
//other validation goes here...
if(empty($_FILES['file']['name'])) {
    $errors['file'] = 'upload file!';
}
//other validation goes here...
echo json_encode($errors);

EDIT: I notice that the name attribute in the input type file is not available/removed by the plugin and the input ID is also overwritten every time i load the page,

//example the input look like where the id="filepond--browser-men6qus3m" change every time i load new file


<input class="filepond--browser" type="file" id="filepond--browser-men6qus3m" aria-controls="filepond--assistant-men6qus3m" aria-labelledby="filepond--drop-label-men6qus3m" accept="image/png">

Thus why i get undefine typoerror and the file not attached

1 Answers

You are going to send a FormData with Ajax request. The problem you've mentioned here is that you want to include the file which is attached using FilePond library. Here is my solution to append FilePond files to a FormData:

$(document).ready(function () {
    pond = FilePond.create(
        document.querySelector('#file'), {
            allowMultiple: true,
            instantUpload: false,
            allowProcess: false
        });

    $("#upload_form").submit(function (e) {
        e.preventDefault();
        var fd = new FormData(this);
        // append files array into the form data
        pondFiles = pond.getFiles();
        for (var i = 0; i < pondFiles.length; i++) {
            fd.append('file[]', pondFiles[i].file);
        }

        $.ajax({
                url: 'fileupload2.php',
                type: 'POST',
                data: fd,
                dataType: 'JSON',
                contentType: false,
                cache: false,
                processData: false,
                success: function (data) {
                    //    todo the logic
                    // remove the files from filepond, etc
                },
                error: function (data) {
                    //    todo the logic
                }
            }
        );
    });
})
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
    <script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script>
    <link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"/>
    <script src="https://unpkg.com/filepond/dist/filepond.js"></script>

<form id="upload_form" method="POST" enctype="multipart/form-data">
    <input type="text" name="username" id="username">
    <input type="file" name="file" id="file" class="filepond">
    <input type="submit" value="Upload"/>
</form>

And on your PHP side, you need can get the files like this:

$errors = [];

if (empty($_POST["username"])) {
    $errors['username'] = 'Enter your name!';
}

// check if file is set and uploaded.
if (!isset($_FILES['file']) || $_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
    $errors['file'] = 'upload file!';
} else {
    $filesNum = count($_FILES['file']['name']);
    // Looping all files
    for ($i = 0; $i < $filesNum; $i++) {
        // same the file
        move_uploaded_file($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i]);
    }
}

// Other validation goes here...
// Return the proper response to the client
// I'll leave this to you

And note that:

  • I've disabled instantUpload and allowProcess on FilePond to prevent auto uploading and processing.
  • Your PHP side needs more validation and also it should return proper response to the Ajax.
Related