0

I have some trouble sending the following html input type to my php script through ajax. I'm guessing that I have to define the file in tje js code hoverver how to do so when I have more variables that are taking information from the same file (se php code)?

<input id="imagefile" class="file" type="file" name="image" />

through this code

$("#addmedia").click(function(ev) {
            ev.preventDefault();
            var p                   = $("#p").val();
            var mediatype           = $("#mediatype option:selected").val();
            var addmediatype        = $("#mediatype option:selected").val();
            var title               = $("#title").val();
            var video               = $("#medialink").val();
            var imagefile           = $("#imagefile").val();

            $.post("lib/action.php", {
                mediatype:      mediatype,
                addmediatype:   addmediatype,
                title:          title,
                video:          video,
                addmedia:       true
            }, function(data) {
                $("#notify").hide().html("<h1>!</h1><h2>" + data + "</h2>").slideDown(500);
                setTimeout(function() { $("#notify").slideUp(500) }, 2500);
            });
        });

so that it works with my php upload script.

In my php code i use following variables to get infro from the file

if( $_POST['p'] == 1 ) {
            $name =     $_FILES['image']['name'];
            $temp =     $_FILES['image']['tmp_name'];
            $type =     $_FILES['image']['type'];
            $size =     $_FILES['image']['size'];

(...)
}
Montague
  • 82
  • 8

1 Answers1

1

When you use $().val for a file field, you're only getting the filename because of security restrictions.

One solution (for IE 10+, Chrome, FF) is to read the file contents using https://developer.mozilla.org/en-US/docs/Web/API/FileReader, base64 encode it and upload it. See Reading client side text file using Javascript

document.getElementById('file').addEventListener('change', readFile, false);

function readFile (evt) {
   var files = evt.target.files;
   var file = files[0];           
   var reader = new FileReader();
   reader.onload = function() {
      console.log(this.result);            
   }
   reader.readAsText(file)
}

Note that there are too many gotchas when uploading files through AJAX and can't possibly address with a concise answer as StackOverflow answers should be.

The easiest workaround is to not send it using AJAX, use a regular form upload, but target a hidden iframe so your page doesn't reload.

See:

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217