I'm trying to upload files using AJAX and I'm hooking in my functions so they get called within admin-ajax. I can't get it to work tough, and I didn't have any idea what was wrong or where to look at all. I narrowed it down, however, by modifying admin-ajax.php a little bit:
// Require an action parameter
if ( empty( $_REQUEST['action'] ) ) {
$response = array(
'error' => 'no action parameter',
'req' => var_export( $_REQUEST, true )
);
wp_send_json( $response );
wp_die( '0', 400 );
}
My AJAX request has dataType: 'json' in it, so my success function does get called(if I remove the $response declaration and the call to wp_send_json, the error one gets called, returning the entire page as a response with the statusText being "parsererror").
Anyway, here's my AJAX script:
$( '#user-file' ).change( function( event ) {
var formData = new FormData();
formData.append( "userfile", $(this)[0].files[0] );
formData.append( "action", "vibesoft_files_upload" );
formData.append( "_wpnonce", vbsoft.nonce_upload );
console.log( formData );
$.ajax({
type: "post",
url: vbsoft.ajax_url,
data: formData,
contentType: "multipart/form-data",
processData: false,
dataType: 'json',
success: function( data ) {
if ( data.error != 'none' ) {
console.log( 'Error: ' + data.error );
console.log( 'Request: ' + data.req );
return;
}
It's not the entire function, which is wrapped inside (function($) { ... })(jQuery);
so I can use $ instead of jQuery. The console.log( 'Request: ' + data.req );
outputs:
Request: array(
)
I also tried outputting the $_POST and $_FILES and they, too, are empty arrays. If I send them back using(instead of the JSON return):
var_dump( $_REQUEST );
exit;
I get array(0) {}
back in the console.
So, yeah, I have no idea why am I getting an empty array...