0

I have been trying hard to know what can be the issue of Uploading image. Tried several ways, but couldn't succeed in Ajax. If I will upload file without using Ajax, it works fine : I am new to AJAX , so thus may be missing some trick.

Moreover, The full form is working perfectly with ajax, but $_FILES is creating a problem . ERROR IS:

Notice: Undefined index: Upload in Z:\xampp\htdocs\webseite\a.php on line 70

What can be the reason ?

I know there are several posts related to that, but none matches with XMLHttpRequest .

Thanks

This is the code.

HTML file has HTML code and Javascript/AJAX code. Second file : a.php has PHP code.

<div class="form-group  mygroup">
          <label   for="name"> Upload (optional) </label>
          <input type="file" class="form-control" name="Upload" id="Upload">

</div>

 <script>
     var xhttp = new XMLHttpRequest(); 
      var Upload_rek=document.getElementById('Upload').value; 

        xhttp.open('GET', 'a.php?&Upload_var='+Upload_rek+'&Senden_var='+Senden_rek, true);
       xhttp.send();   
 </script>  

<?php
 $target = "uploads/".basename($_FILES['Upload']['name']);
 ?> 
Nabeel
  • 1
  • 5

1 Answers1

2

You need to append your file using FormData

var formData = new FormData();
formData.append(file, file);
xhr.send(formData);

In your current code state you don't send/upload the file to the server at all.

mele
  • 66
  • 10
  • So using FormData is the only way ?? By using PhP, the same sort of Code works. but not in Ajax . So according to your answer, : with ajax, need to use FormData() – Nabeel Jun 13 '17 at 20:17
  • Yes, you have to send the file to the server so PHP will be able access it. If it's an image, pdf, text file etc.you might be able to convert it to a base64 string and send it as a standard GET/POST value but you rather stick with FormData – mele Jun 13 '17 at 20:21
  • thanks for your explanation By the way. it looks funnier to me that other variables are working perfectly with this style of coding, but Upload files doesnot work. So thought , might be missing something but not a case. I will now work via FormData to overcome this issue.. Hope for the best :) – Nabeel Jun 13 '17 at 20:25