-1

I want to upload image without page loading, here sendImageFile is the value of file field. Now when I trying to upload any file from file_upload_to_user.php but every time $_FILES["sendImageFile"]["name"] returns null value.

<form enctype="multipart/form-data" method="post" name="img_upload_form" id="img_upload_form" action="file_upload_to_user.php">
  <input name="sendImageFile" id="sendImageFile" type="file" accept=".png, .jpg, .jpeg"/>
  <input type="submit" name="photoUploadToSend" id="photoUploadToSend" style="display:none" />                        
</form>

JS

var frm = $('#img_upload_form');
frm.submit(function (ev) {
  var sendImageFile = document.getElementById("sendImageFile").value;
  var to_hash = "000000000";
  var dataString = 'sendImageFile='+sendImageFile+"&to_hash="+to_hash;
  $.ajax({
    type:"POST",
    url:"file_upload_to_user.php",
    data:dataString,
    cache:false,
    success: function(info) { alert(info);}
  });
}
document.getElementById("sendImageFile").onchange = function change(){ 
  // Upload image
  document.getElementById("photoUploadToSend").click();             
}
Endless
  • 34,080
  • 13
  • 108
  • 131
Das
  • 1
  • 2

2 Answers2

0

If you want to upload a file with ajax then you have to do it with FormData. And to send a formData with jQuery you need to send two other properties to to disable sending wrong stuff. so it's just easier to use fetch...

var form = document.getElementById("img_upload_form")
var fd = new FormData(form)

fetch("file_upload_to_user.php", {method: 'POST', body: fd})

To send a formdata with jQuery ajax you have to set this two:

processData: false,
contentType: false,
Endless
  • 34,080
  • 13
  • 108
  • 131
0

You need to use formData

var formData = new FormData();
formData.append('file', $('#sendImageFile')[0].files[0]);
formData.append('to_hash',"000000000");

$.ajax({
       url : 'file_upload_to_user.php',
       type : 'POST',
       data : formData,
       processData: false,//prevent automatic processing
       contentType: false,//do not set any content type header
       success: function(info) { alert(info);}
});
meda
  • 45,103
  • 14
  • 92
  • 122