ajax – Why is the file not uploading to the server?

Question

On wordpress page i am using inline vue, because form is too complex.

let formData = new FormData();
formData.append("action", "topcare");
formData.append("nonce", true_object.nonce);
formData.append("administration_desc", this.controls.administration_desc);
formData.append("administrator_file", this.controls.fileList[0]);

fetch(url, {
        method: 'POST',
        body: formData,
    })
    .then(res => res.json())
    .then(res => {
        this.formSuccess = true;
        this.formWasSent = true;
        this.loading = false;
        console.log(JSON.stringify(res, null, 4));
        setTimeout(() => {
            this.formSuccess = false;
        }, 2000)
    }).catch(error => {
        this.formSuccess = false;
        this.formWasSent = true;
        this.loading = false;
        console.log(JSON.stringify(error, null, 4));
    })

As i understood, i don’t need to set Conte-type: multipart-form-data in fetch, because it will be set automaticaly.

Server php file:

<?php
function true_localize_example()
{
    wp_enqueue_script('truescript', get_template_directory_uri() . '/vue/topcare/ajax.js', [], null, false);
    wp_localize_script('truescript', 'true_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('feedback-nonce'),
    ));
}
add_action('wp_enqueue_scripts', 'true_localize_example');
add_action('wp_ajax_topcare', 'ajax_form');
add_action('wp_ajax_nopriv_topcare', 'ajax_form');
function ajax_form()
{
    if (!wp_verify_nonce($_POST['nonce'], 'feedback-nonce')) {
        wp_die('Data was recieved from another address');
    }
    if (!empty($_POST['checkField'])) {
        wp_die('This is a spam');
    }

    die(json_encode(array('type' => 'files', 'text' => $_FILES))
    

And $_FILES is empty.
Why?

Thanks in advance.

0
serii 2 months 2022-06-07T04:44:41-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse