1

I am trying to upload a file using AJAX and PHP.

I already do it using forms:

<form action="upload.php" method="POST">
<input type="file" id="idFile" name="fileName" />
</form>

And it works very well, but I really need to do it with AJAX.

I already have my php script which uploads the file. I want this script to be excecuted whith AJAX. I want my javascript function to do something like this:

function uploadFile(file) {
    var url = "upload.php?file="+file; //<-- Can I do this?

    xmlhttp = GetXmlHttpObject();
    if (!xmlhttp) {
       alert ("Browser does not support HTTP Request");
       return;
   }
   var xml = xmlhttp;
   xmlhttp.onreadystatechange = function () {
      if (xml.readyState == 4) {
         alert("THE FILE WAS UPLOADED");
      }
   };
   xmlhttp.open("GET",url,true);
   xmlhttp.send(null);

   return true;
}

My question is: Is it posible to pass a file-type variable this way? If not, which is the way I can pass the file variable? Can I use document.getElementById("idFile").value ?

I hope someone could help me Thanks!

mauguerra
  • 3,728
  • 5
  • 31
  • 37

3 Answers3

3

You can't upload files via AJAX. You should use hidden iframe instead.

File upload by ajax is introduced in XHR2 FormData object but this is not supported by old browsers. See browsers compatibility table.

antyrat
  • 27,479
  • 9
  • 75
  • 76
1

Unfortunately you can't upload files with Ajax. Have a look at http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/

boeing
  • 302
  • 7
  • 19
1

I solved the problem in this way.

<form method="POST" id="formLic" name="formLic" enctype="multipart/form-data">
   <label for="lnumero">Número: </label>
   <input type="text" id="lnumero"/>
   <label for="larchivo">Archivo: </label>
   <input type="file" id="larchivo"/>
</form>
<script>
      $(document).ready(function() { 
        $("form#formLic").submit(function(){
            var formData = new FormData($(this)[0]);
            $.ajax({
                url: "nuevo/uploadInsert.php", // file where you save your data and files
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    // action or message 
                }
            });
            return false;
        });
    });
</script>
Snd'
  • 44
  • 4