Reputation: 457
I'm using an ajax call to upload a file, handled by PHP. The file should be placed in a specific directory based on a jquery variable. I can get the file to upload, but cannot pass the variable along with the file. PHP reports an undefined index error.
Ajax code:
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
I tried changing the data property to "fd+'&myVar='+myVar, however PHP cannot parse the data correctly and returns undefined index error for both the $_FILES['file'] variable as well as the $_POST['myVar'] variable.
How can I send both the file and a variable?
Upvotes: 1
Views: 3823
Reputation:
Refer to $.ajax
jQuery API Documentation.
It is clearly stated that data
should be an object with key-value pairs representing data accepted by server-side script. Whatever, not sure why jQuery seems to not accept your data. Maybe you should try this out manually.
Since your test.php
accepts POST
data as myVar
your jQuery Ajax configuration should probably look like
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myVar: document.getElementById('select').files[0]
},
success: function(e){
// some code here
}
});
Upvotes: -1
Reputation: 3903
If you need another form field, call fd.append a second time:
fd.append('file', document.getElementById('select').files[0]);
fd.append('myVar',myVar);
Upvotes: 7
Reputation: 97672
You can append values other than files to a formdata object.
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
fd.append( 'myVar', myVar);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
Upvotes: 4