Reputation: 61
I'm trying to perform an image upload via Ajax setting FormData object however when form data is submitted the _FILES variable remains empty and get HTTP_RAW_POST_DATA=[object Object] not sure what the problem is here but would really appreciate some help on this.
code snippets below:
<form id="test_upload_form" action="/inventory/fileImport">
<input id="test_file" type="file" name="superfile">
<input type="hidden" name="nonce" value="<?=$this->nonceField()?>">
<input type="submit" name="submit">
</form>
<script>
$('#test_upload_form').on('submit', function(e){
e.preventDefault();
var fileInput = $('#test_file');
debugger;
var file = ($('#test_file'))[0].files[0];
var formData = new FormData($(this));
formData.append('file', file);
$.ajax({
url: '/inventory/fileImport',
type: 'POST',
data: formData,
cache: false,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
console.log(data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
});
</script>
Just amended the Javascript to the below and it seems to be working now. Just doesn't work with Jquery.
$('#test_upload_form').on('submit', function(e){
e.preventDefault();
var file = ($('#test_file'))[0].files[0];
var formData = new FormData(document.getElementById("test_upload_form"));
formData.append('file', file);
var request = new XMLHttpRequest();
request.open("POST", "/inventory/fileImport");
formData.append("serialnumber", 'asdasdsadas');
request.send(formData);
});
Upvotes: 1
Views: 531
Reputation: 61
FormData is waiting for a standard javascript DOM object and you are using a jQuery object
Try using
var formData = new FormData(document.getElementById("test_upload_form"));
instead of $(this)
or you can also convert your jQuery object using $(this)[0]
Upvotes: 1