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: </label> <input type="text" name="lastname" id="lastname" required/><br/>
<label>Firstname: </label> <input type="text" name="firstname" id="firstname" required/><br/>
<label>Middlename: </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.