1

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;
4
  • 1
    show us your form and ajax code Commented Apr 6, 2015 at 19:14
  • i have added the ajax code Commented Apr 6, 2015 at 19:24
  • Check this: stackoverflow.com/questions/23980733/… Commented Apr 6, 2015 at 19:30
  • i dont want to use jquery. what i sthis line doing? var file_data = $('#sortpicture').prop('files')[0]; Commented Apr 6, 2015 at 19:34

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1
$photo_location = $_FILES['file']['photo'];

10 Comments

try printing the variable: print_r($_FILES); and see what you get?
try adding this into your form tag: enctype="multipart/form-data"
sorry for not posting my form but i have it.
i tried printing the photo i get from this var photo = document.getElementById("photo").value; and i get this path C:\fakepath\images.jpg
Can you please post your php code so that I can see how you are getting other values correctly (i.e. name, price, quantity and etc)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.