2

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

amrezzd
  • 1,787
  • 15
  • 38
YEUNG_SANG
  • 61
  • 1
  • 6
  • please do not edit answers to reply. Just put a comment with the button below the answer – Lelio Faieta May 18 '21 at 12:24
  • if you read the documentation [here](https://pqina.nl/filepond/docs/patterns/api/server) you will see that server is a path relative to where you run the js script where the server api is located. http:// is used if the endpoint is on a different server. otherwise `./` is used for the same folder and so on – Lelio Faieta May 18 '21 at 12:29

1 Answers1

3

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.
amrezzd
  • 1,787
  • 15
  • 38
  • @ubongo I updated the answer, please let me know if it worked. – amrezzd May 17 '21 at 18:27
  • it works, on validation no the so called unidefined name on field, but the trouble, is when i click the button to submit data, it send only name no file sent, please look my ajax code, and when i ignore validation for name, and remove all ajax code, and replace the server url in filepond options to server: 'name of php script' it works why? – YEUNG_SANG May 17 '21 at 18:45
  • When I inspect the form data on console there is only field file with no value while the field name have the value – YEUNG_SANG May 17 '21 at 18:52
  • @ubongo Could you please try the updated answer. – amrezzd May 17 '21 at 18:54
  • @ubongo I guess the new problem is about your URL. I kept it as it was on your question. – amrezzd May 17 '21 at 19:59
  • Thanks, now it send the file as base64 encoded and other data – YEUNG_SANG May 18 '21 at 22:13
  • @ubongo YW, I've updated the answer to use blob instead of base64. I think this is a better way. – amrezzd May 20 '21 at 06:04
  • Thanks bro, you nailed it, my last question here but i'm so sorry, I want to remove file from the user after user click submit, Tried working with `.filepond--file-wrapper` by using `.d-none` bootstrap class by calling `$('.filepond--file-wrapper').addClass('d-none'); ` after success function, yes it hide but the drug drop label not showing as previous until user reload page, Any idea please? – YEUNG_SANG May 20 '21 at 21:12
  • @ubongo You can use `pond.removeFiles()` to remove them all. – amrezzd May 21 '21 at 04:27