Skip to content

Instantly share code, notes, and snippets.

@danielzzz
Last active January 18, 2021 14:06
Show Gist options
  • Select an option

  • Save danielzzz/0fb7c591bbaf9d1a54b56a1a260763cc to your computer and use it in GitHub Desktop.

Select an option

Save danielzzz/0fb7c591bbaf9d1a54b56a1a260763cc to your computer and use it in GitHub Desktop.

Revisions

  1. danielzzz revised this gist Jan 18, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion wpfetch.js
    Original file line number Diff line number Diff line change
    @@ -22,7 +22,7 @@ fetch(url, { // Your POST endpoint
    method: 'POST',
    credentials: 'same-origin',

    body: data, // This is your file object
    body: data, // This is what you're sending (files and variables)
    }).then(
    (response) => response.json(), // if the response is a JSON object
    ).then(
  2. danielzzz created this gist Jan 18, 2021.
    34 changes: 34 additions & 0 deletions wpfetch.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    // 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 your file object
    }).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