Javascript – AJAX – Uploading a file (HTML 5) & PHP


I feel completely out of my depth but I feel so close..

I'm trying to Upload a file using AJAX. I found this tutorial and it seemed to be going quite well until the end. I can't seem to access the file in PHP i.e. using $_FILES["foo"]["name"];
and I'm not sure how to upload using other techniques.

I'm not looking for the code to be perfect, just kept simple so I can understand what's going on. Thanks in advance 🙂

Here is my server side code:


page title


  <form onsubmit='showUser(); return false;' enctype='multipart/form-data'>
    <input id='the-file' name='file' type='file' />
    <input type='submit'>
  <br />

  <div id='txtHint'><b></b></div>



function showUser(str)
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var foo = file.fileName;

if (str=="")
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 {// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
 xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
 xmlhttp.setRequestHeader("X-File-Type", file.type);
 xmlhttp.setRequestHeader("X-File-Name", foo);



$postdata = file_get_contents("php://input");

echo "Name: " . $_SERVER['HTTP_X_FILE_NAME'] . "<br />";


Best Solution

Have a look at

Writing straight JavaScript is no longer such a great idea. Using libraries as demonstrated on that page, you can create a much more powerful file upload which supports multiple files, resumeable downloads, progress bar and many other features that you would really have to sweat to implement yourself but which give your user a better experience.