Last active
January 18, 2021 14:06
-
-
Save danielzzz/0fb7c591bbaf9d1a54b56a1a260763cc to your computer and use it in GitHub Desktop.
fetch wp (wordpress) example file upload how to avoid error 400 wp api json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dont forget to activate your endpoint in the plugin | |
// $this->loader->add_action('wp_ajax_nopriv_upload_answer', $plugin_public, 'upload_answer'); | |
// $this->loader->add_action('wp_ajax_upload_answer', $plugin_public, 'upload_answer'); | |
//--------- js code --------------------- | |
const url = "/admin-ajax.php"; | |
//el -> an file input element | |
const data = new FormData(); | |
//append files | |
for (const file of el.files) { | |
console.log('adding', file.name); | |
data.append('files', file, file.name); | |
} | |
// dont forget to put the api endpoint action | |
data.append('action', 'upload_answer'); | |
// any other data you want to send | |
data.append('case_id', 'test variable); | |
// jQuery.post(url, { action: 'upload_answer' }); | |
fetch(url, { // Your POST endpoint | |
method: 'POST', | |
credentials: 'same-origin', | |
body: data, // This is what you're sending (files and variables) | |
}).then( | |
(response) => response.json(), // if the response is a JSON object | |
).then( | |
(success) => console.log(success), // Handle the success response object | |
).catch( | |
(error) => console.log(error), // Handle the error response object | |
); | |
// in the php file handle files in $_FILES and other data in $_POST |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment