Download a file with PHP with Ajax

advertisements

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!


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>