I'm trying so hard to make this working and none of the solutions here or anywhere else seems to work for me. I don't know what I'm doing wrong and maybe I have a misunderstanding of how things work.
I have some data, including an input
of type file
, all out of a html form
. I want to send them all together through one ajax
request and upload the file and also being able to handle the other data.
So I created an array with all the data(including the file data) with the name the_data
and passed it to the ajax
function.
And it doesn't work. The problem is not server side because the ajax
request is never made. The problem is client side but I don't understand what might be the problem.
So here is my code:
function sentDataToSql(pos) {
var data = new FormData();
jQuery.each(jQuery('#photo-upload')[0].files, function(i, file) {
data.append('file-'+i, file);
});
var numbers = $('#numbers').val();
var my_address = $('#my-address').val();
var signals=$('.signals').text();
var date=new Date();
var month=date.getMonth()+1;
var day=date.getDay();
var year=date.getFullYear();
var finaldate=year+'-'+month+'-'+day;
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var the_data={
nums:numbers,
address:my_address,
type:'sometype',
lat:pos['lat'],
lng:pos['lng'],
sigs:signals,
time:time,
date:finaldate,
pic:data //If I remove this everything will work(but of course the file won't be sent)
};
if(my_address!=''){
$.ajax({
type:'POST',
url:'../index.php',
data:the_data,
})
}else{
alert('Please .....! ')
}
}
Non of the above data is in a form
and all are outside a form
as well as the input element with type file
which looks like this:
<input type="file" name="photo" style="opacity:0;" id="photo-upload">
Here is my console log error :
TypeError: 'append' called on an object that does not implement interface FormData.
Edited code still not working after trying to put all data into a FormData
object, and I get the same error as above:
function sentDataToSql(pos) {
var numbers = $('#numbers').val();
var my_address = $('#my-address').val();
var signals=$('.signals').text();
var date=new Date();
var month=date.getMonth()+1;
var day=date.getDay();
var year=date.getFullYear();
var finaldate=year+'-'+month+'-'+day;
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var data = new FormData();
jQuery.each(jQuery('#photo-upload')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('nums',numbers);
data.append('address',my_address);
data.append('type','homeless');
data.append('lat',pos['lat']);
data.append('lng',pos['lng']);
data.append('sigs',signals);
data.append('time',time);
data.append('date',date);
if(my_address!=''){
$.ajax({
type:'POST',
url:'../index.php',
data:data,
})
}else{
alert('Please locate your location first.')
}
}