I keep running into an issue getting the file(s) added in AJAX so that the server ajax function can process the data. How can I get the $_FILES to be passed the same as with the default action (built into form elements)?
HTML Form
<form id="frmImport" name="frmImport" method="post" enctype="multipart/form-data" >
<input id="file_import" name="importData" type="file" />
<br/>
<button id="btn_import" type="submit" >Import</button>
</form>
JavaScript
jQuery(document).ready(function($) {
//This is already setup and sent from the server side, and is
// is used to prevent unauthorized users from uploading data.
var importnonce = "3x4mpl3f4k3n0nc3";
$('#frmImport').submit(function(e) {
e.preventDefault();
// CHECK FOR ANY ERRORS HERE.
// IF ERRORS EXIST, RETURN FALSE TO END OPERATIONS.
var formData = new FormData();
formData.append('action', 'ajax_handler_import');
formData.append('_ajax_nonce', importNonce);
// Issue occures here. PHP gets a string '[object FormData]'.
var importFiles = $('#file_import')[0].files;
formData.append('uploadFiles', importFiles);
jQuery.ajax({
url: ajaxurl,
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(jqXHR, settings) {
console.log("Haven't entered server side yet.");
},
dataFilter: function(data, type) {
// Used to parse data, and possibly check for errors.
console.log("JSON string echoed back from server side.");
},
success: function(data, textStatus, jqXHR) {
console.log("Back from server-side!");
// Checking errors that may have been caught on the server side that
// normally wouldn't display in the error Ajax function.
if (data.msg != 'success') {
alert(data.error);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("A JS error has occurred.");
},
complete: function(jqXHR, textStatus) {
console.log("Ajax is finished.");
}
});
return false;
});
});
PHP Server/Handler
<?php
class server {
function ajax_import_handler() {
check_ajax_referer("ajax_handler_import");
$rtnData = new stdClass();
$rtnData->msg = 'success'; //For signifying Server errors
$rtnData->error = ''; //For displaying custom error messages or using the try/catch method
//Do Stuff
foreach ($_FILES as $key => $value) {
//GET FILE CONTENT
$file_array[$key] = json_decode(file_get_contents($value['tmp_name']));
}
// Do more stuff with file(s).
// Add stuff to $rtnData.
echo json_encode($rtnData);
}
}
?>