FormData object is only getting file input and not other inputs such as text

I'm fairly new with using FormData object and still trying to familiarize myself with how it works. So, I managed to post a video file to a php script which handles uploading/moving of video file to a folder. However, I can't pass or post other form input information such as text that is typed in form's text fields.

My goal is to pass/post all formdata (video file and texts on input fields) to a php script. I tried to var_dump the $_POST array to see if there are other data posted aside from $_FILES['file'].

I'm able to get the file input but not the text inputs. I want to send all of the formdata in just one button click.

Below is what I get out from var_dump() -ing $_POST and $_FILES

array(0) {
}
array(1) {
  ["file"]=>
  array(5) {
    ["name"]=>
    string(48) "How to Create App Shortcut on Ubuntu Desktop.mp4"
    ["type"]=>
    string(9) "video/mp4"
    ["tmp_name"]=>
    string(14) "/tmp/phprG6kRC"
    ["error"]=>
    int(0)
    ["size"]=>
    int(10522522)
  }
}

It shows array(0){} for var_dump($_POST)

index.php

<form id="myForm" method="POST" enctype="multipart/form-data">

    <label>Lastname: &nbsp;</label> <input type="text" name="lastname" id="lastname" required/><br/>
    <label>Firstname: &nbsp;</label> <input type="text" name="firstname" id="firstname" required/><br/>
    <label>Middlename: &nbsp;</label> <input type="text" name="middlename" id="middlename" required/><br/>
    <label class="modal_label" id="modalLbl_browseVideo">
        Select Video
        <input type="file" name="file" id="file_input" value="Select Video" accept="video/*"/>
    </label>

    <button name="myButton" id="myButton">
        Upload
    </button>
    <br/>
    <label id = "errorLabel"></label>

</form>

<script src="js/jquery-3.3.1.js"></script>
<script src="js/index.js"></script>

index.js

$('#myButton').click(function(){
    upload(); 
});

function upload() {
    var formData = new FormData($('#myForm')[0]); //initialized with myForm 

    $.ajax({
        url: 'upload_video.php',
        type: 'POST',
        data: formData,
        cache: false;
        processData: false,  // tell jQuery not to process the data
        contentType: false,  // tell jQuery not to set contentType
        success: function (data) {
            console.log(data);
            alert(data);
        },
        error: function (x, e) {
            if (x.status == 0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status == 404) {
                alert('Requested URL not found.');
            } else if (x.status == 500) {
                alert('Internal Server Error.');
            } else if (e == 'parsererror') {
                alert('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknown Error.\n' + x.responseText);
            }
        }
    });
}

upload.php

var_dump($_POST);
var_dump($_FILES);

The way I understand it is that var formData = new FormData($('#myForm')[0]); is initialized with all the data that the form has and contained in formData variable. But it's only getting the video file input on var_dump()

How come it's not able to display the other form data values that were posted such as the last name, first name and middle name?

I'd appreciate any suggestion.

Thank you.

1 answer

  • answered 2018-07-11 06:58 jordan

    I was able to solve my problem by appending the values to formData object. Works best for what I'm trying to do.

    index.js

    function uploadVideo() {
        var formData = new FormData();
        var videoFile = $("#file_input")[0].files[0];
        formData.append('file', videoFile);
        formData.append('lastname',$('#lastname').val());
        formData.append('firstname',$('#firstname').val());
        formData.append('middlename',$('#middlename').val());
    
        $.ajax({
            url: 'upload_video.php',
            type: 'POST',
            data: formData,
            cache: false,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: function (data) {
                console.log(data);
                // alert(data);
            },
            error: function (x, e) {
                testForError(x,e);
            }
        });
    }
    

    upload.php

    echo $_POST['lastname'];
    echo $_POST['firstname'];
    echo $_POST['middlename'];
    

    I tested it and I was able to get the lastname, firstname, and middlename values as response from success: function(data){} when I console.log(data);

    This should serve as reference for others to try and possibly solve their problem relating to this.