I'm trying to upload files in wordpress using admin-ajax.php
I have this code in my functions.php file
function upload_docs(){
var_dump($_FILES);
}
add_action('wp_ajax_nopriv_upload_docs', 'upload_docs');
add_action('wp_ajax_upload_docs', 'upload_docs');
The function at the moment is a test that I want to use to debug what informations are passed from the front-end that is a vue app hosted in a page template.
I've corectly loaded and localized the vue css and js files and after the build, in my localhost I'm able to pass the other forms I have configured on my functions file
On the front-end side, the vue app have this method that will add the needed informations to the wordpress backend
sendUploadForm(){
let documents = this.$refs.uploadedFiles.files
let userData = new FormData()
for(let i = 0; i < documents.length; i ){
userData.append('file[]', documents[i])
}
userData.append('action', 'upload_docs')
axios.post(wp_param.ajaxurl, userData).then( res => {
console.log(res)
}).catch( e => console.log(e) )
}
What is going wrong with the code? I will always get a 500 error status code ERR_BAD_RESPONSE
and I don't know if the function is called because I'm unable to see any var_dump
or var_export
from php. I've tried to enable the debug in wp config file but nothing changed.
Any suggestion?
CodePudding user response:
Add these additional two lines under your WP_DEBUG
one, make the error happen again, and check in the folder wp-content/
if you see a new file debug.log
.
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
Consider:
- Implementing nonces and permission checks to protect your endpoints
- If only logged in users are supposed to be able to upload files, ensure the no_priv method is properly locked down
- Using a custom REST API endpoint instead of admin-ajax https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/
- Terminate your function with wp_die(); when using AJAX in WordPress