I'm trying to upload file using ajax and php, but the console output is something like this Message: Undefined index: photo
Here is the html code:
<input id="photo" name="photo" type="file" onchange="$('#preview')[0].src = window.URL.createObjectURL(this.files[0])" required/>
<input type="button" value="Upload" id="btn_photo" />
Ajax code:
var form_data = new FormData();
form_data.append('file', 'photo'); # html input name
$.ajax({
url : "<?php echo base_url('upload') ?>",
type : "POST",
data : form_data,
contentType : false,
cache : false,
processData : false,
enctype : 'multipart/form-data',
dataType : 'JSON',
success: function(data) {
var obj = $.parseJSON(JSON.stringify(data));
if(obj['status']) {
alert('success');
}
},
error: function (data) {
console.log("AJAX error in request: " + JSON.stringify(data, null, 2));
}
});
and this is the php code to handle upload process,
$image_name = $_FILES[$fieldname]['name'];
since the $fieldname
is a variable to store html input file name, then it will replaced with value photo
I'm not using form tag to upload the file in my html code, did i miss something? Can someone please help me with the error?
EDIT
According to this ref FormData API I should append file data like this
formData.append('userpic[]', myFileInput1.files[0], 'chris1.jpg');
So, i updated these line
var form_data = new FormData();
form_data.append('file', 'photo'); # html input name
into this
var form_data = new FormData();
var file = document.getElementById("photo").files[0];
form_data.append('file', file, $("#photo").val());
Then i got this error undefined offset 0
Can someone please help?