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!

2
  • This might help: stackoverflow.com/questions/1686099/… Commented Dec 10, 2013 at 23:04
  • 1
    @Fred-ii- Thanks I know, I didn't writte it complete because I already have that way working very well. Commented Dec 10, 2013 at 23:14

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.