Home Ask Login Register

Developers Planet

Your answer is one click away!

James Walker February 2016

Combine $_FILES and $_POST into one AJAX call with Javascript only

I am having difficulty sending an ajax call that contains both a file and a string. I have no difficulty making either post or file, but not both together. I need this in pure Javascript, which i am more proficient than Jquery.
here is the code i am working with...

    function uploadFile(){
var title = _('title').value;
var genere = _('genere').value;
var stars = _('stars').value;
var description = _('description').value;
    var file = _("video").files[0];
     //alert(file.name+" | "+file.size+" | "+file.type);
    var formdata =  new FormData();
formdata.append("video", file);
formdata.append("title", title);
formdata.append("genere", genere);
formdata.append("stars", stars);
formdata.append("description", description);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "video_php/video_upload.php");
function progressHandler(event){
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
function completeHandler(event){
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
function errorHandler(event){
    _("status").innerHTML = "Upload Failed";
function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";

This is the php.....

$fileName = '';
$fileTmpLoc = '';
$fileType = '';
$fileSize = '';
$title = '';
$genere = '';
$stars = '';
$description = '';
$retn=  '';
if (!isset($_FILES["video"]["name"])) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";


Ohgodwhy February 2016

Looks like you want the value of _('title') to be added to the formdata.

Given that you have this:

formdata.append("video", file);

All you need to do is this:

formdata.append('title', title);

The FormData object will handle the transmission of the file, and title will be available as $_POST['title'];

Post Status

Asked in February 2016
Viewed 2,724 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life