0

I am trying to send with ajax a photo from javascript to php. I have this input in html:

<input type="file" class="input-field" id="photo" name="photo">

this in javascript:

var photo = document.getElementById("photo").value;

and this in php:

$photo_location = $_FILES['photo']['tmp_name'];

I am using ajax post to send the photo and some other data in php. All other data are received correctly in php except the photo. is the getelementbyid .value method which gets the photo wrong ? i get an error undefined index photo from php.

xmlhttp.open("POST", "ajaxpost.php");
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    var payload = "name=" + name + "&price=" + price + "&quantity=" + quantity + "&description=" + description + "&photo=" + photo;
    payload = payload.replace("%20", "+");
    payload = payload.replace("%3D", "=");

    xmlhttp.send( payload );

    return false;
user784512
  • 35
  • 2
  • 9

2 Answers2

1

the error is that you send file as normal input so php will recieve it in $_POST not $_FILES.

you can do it using FormData like this:

var photo = document.getElementById("photo");

var data=new FormData();
//from inputs
data.append(photo.name,photo.files[0]);
data.append('name',name);
data.append('price',price);
data.append('quantity',quantity);
data.append('description',description);

var xmlhttp=new XMLHttpRequest()
xmlhttp.open("POST", "ajaxpost.php");
xmlhttp.send(data);
Omar Elawady
  • 3,300
  • 1
  • 13
  • 17
0
$photo_location = $_FILES['file']['photo'];
Luke
  • 11,426
  • 43
  • 60
  • 69
The Guest
  • 698
  • 11
  • 27