Ajax file upload in Wordpress - can't pass FormData
try this :
jQuery(document).on('click', '#submit', function(e){
e.preventDefault();
var fd = new FormData();
var file = jQuery(document).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
fd.append('action', 'fiu_upload_file');
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
});
php
function fiu_upload_file(){
var_dump($_FILES);
exit();
}
add_action('wp_ajax_fiu_upload_file', 'fiu_upload_file');
add_action('wp_ajax_nopriv_fiu_upload_file', 'fiu_upload_file');
Works whith any input(one or many simple or multiple), textarea, select in your form (WP 5.0.3)
$('#form').submit(function(e) {
e.preventDefault();
var form = $(this);
var formdata = (window.FormData) ? new FormData(form[0]) : null;
var data = (formdata !== null) ? formdata : form.serialize();
formdata.append("action", "fiu_upload_file");
$.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(data){
if(data.error == 'true') {
$('.msg').html(data.true);
}
else {
$('.msg').html(data.false);
// your code if you want an action ...
};
}
});
});
and php for only the files
foreach ($_FILES as $file) :
if($file['error'] == UPLOAD_ERR_NO_FILE) :
continue;
endif;
$valid_ext = array( 'jpg' , 'jpeg' , 'png' , 'doc' , 'docx' , 'pdf' , 'xls' , 'xlsx');
$extension_upload = strtolower( substr( strrchr($file['name'], '.') ,1) );
if ( in_array($extension_upload,$valid_ext) ) :
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$msg_true = 'Upload ok ';
else :
$msg_error = 'Upload error';
endif;
endforeach;
$result = !isset($msg_error);
$msg = array();
if($result) :
$msg['error'] = 'true';
$msg['true'] = $msg_true;
else :
$msg['error'] = 'false';
$msg['false'] = $msg_error;
endif;
header('Content-Type: application/json');
echo json_encode($msg);