0

I'm trying to build an application which allows for file uploads in PHP. When the file is uploaded, a download link should be appended to a specific div. I am using an ajax call to run the php script so that I can have the file download link echoed without getting stuck on the php page. (I hope that makes sense.)

Here is the html:

<form action="php/upload.php" method="POST" enctype="multipart/form-data" id="uploadform">
                Select file to upload:
                <input type="file" name="fileToUpload" id="file">
                <input id="create" type="submit" value="Upload File">
</form>

Here is the external javascript/jquery that makes the ajax call:

$(function () {
  $('form').on('submit', function (e) {
          //prevents reloading of page
          e.preventDefault();
          //get file data
          var file_data = $("#file").prop("files")[0];
          var form_data = new FormData();
          form_data.append('file', file_data);
          //run upload.php script and append result to draggable block
          $.ajax({
            type: 'post',
            url: 'php/upload.php',
            cache: false,
            data: form_data,
            success: function (data) {
              $( "#draggable"+i).append(data);
              i++;
            }
          });

        });
});

And here is the external php script that is supposed to upload the file:

<?php

    $target_path = "../uploads/";
    $target_path = $target_path . basename( $_FILES[ 'fileToUpload' ][ 'name' ] );

    if ( move_uploaded_file( $_FILES[ 'fileToUpload' ][ 'tmp_name' ] , $target_path ) ){
        //echo '<a href=' . $target_path . ' download>Download</a>';
    } 
    else {
        echo $target_path;
        //var_dump($_FILES);
    }

I get the following error: Uncaught TypeError: Illegal invocation

The problem came from trying to pass 'form_data' in the ajax call. I am trying to do that because the $_FILES array was coming up empty once the php script was ran. I need a way to make sure the file that I'm uploading gets stored in that array.

1

1 Answer 1

4

Resolved it myself. Needed to add a couple things to the ajax call:

$.ajax({
            type: 'post',
            url: 'php/upload.php',
            cache: false,
           ** contentType: false, **
           ** processData: false, **
            data: new FormData(this),
            success: function (data) {
              $( "#draggable"+i).append(data);
              i++;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.