0

im having trouble in uploading a single file by ajax . here is my code.

JS file

var _submit = document.getElementById('fileInputBox');
var formData = new FormData();
formData.append('upload', 'upload'); 
formData.append('SelectedFile', _submit.files[0]);

$('#fileInputBox').on('change', function (e) {
  e.preventDefault();

  $.ajax({
    url: 'upload2.php',
    type: 'POST',
    data: formData,
    dataType: 'json' ,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (data) {
       $('#sep_s').html(data.msg); 
    }

 });

  // return false;
});

HTML file

  <form action="" method="post" enctype="multipart/form-data" name="UploadForm" id="UploadForm">

     <div id="AddFileInputBox">
          <input id="fileInputBox" style="margin-bottom: 5px;" type="file"  name="file"/>
     </div>
  </form>

PHP file

  if(isset($_POST['upload']))
  {
     $ImageName         = $_FILES['file']['name'];
     $ImageSize         = $_FILES['file']['size'];
        $TempSrc        = $_FILES['file']['tmp_name'];
      $ImageType        = $_FILES['file']['type'];
    ..........

And the error im getting is

Notice: Undefined index: file in G:\installed here\upload2.php on line 16
Notice: Undefined index: file in G:\installed here\upload2.php on line 17
and so on.

whats is wrong here ?

Karim Daraf
  • 226
  • 2
  • 9

2 Answers2

1

One problem I can see, is that you attach your image at page-load, not when it actually gets set / changes.

You should put that code in the event handler:

$('#fileInputBox').on('change', function () {

  // put this inside the function so that its get set when you assign a value
  var _submit = document.getElementById('fileInputBox');
  var formData = new FormData();
  formData.append('upload', 'upload'); 
  formData.append('SelectedFile', _submit.files[0]);

  $.ajax({
    url: 'upload2.php',
    type: 'POST',
    data: formData,
    dataType: 'json' ,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (data) {
       $('#sep_s').html(data.msg); 
    }

  });
});
jeroen
  • 91,079
  • 21
  • 114
  • 132
0

You use SelectedFile as the parameter in formdata but use file in php, e.g

$ImageName = $_FILES['SelectedFile']['name'];

Also you need to get the file to upload inside the change event handler, that is when the file is actually selected.

$('#fileInputBox').on('change', function (e) {
  var _submit = document.getElementById('fileInputBox');
  var formData = new FormData();
  formData.append('upload', 'upload'); 
  formData.append('SelectedFile', _submit.files[0]);
  ...
Musa
  • 96,336
  • 17
  • 118
  • 137