1

I have a form with a file type input. I want to be able to capture the image attached to this input in JavaScript/jQuery and pass it to my PHP function to then upload to my WordPress media. Using the WordPress media_handle_upload() function which according to the docs requires an index of the $_FILES array that the file was sent as the first parameter.

Here's my attempt so far:

HTML

<form id="company-logo-form" method="post" action="#" enctype="multipart/form-data">
    <input type="file" name="company_logo" multiple="false" id="logo-test"/>
    <input class="btn bg green" name="upload_company_logo" type="submit" value="Upload Image" />
</form>

Javascript

$('#company-logo-form').on('submit', function(e) {
    e.preventDefault();
    let logo = $('#logo-test').prop('files');

    $.ajax({
        url: ajax_url,
        type: 'POST',
        // dataType: 'html',
        data: {
            company_logo: logo,
            action: 'uploadCompanyLogo'
        },
        error: function(res) {
            console.log(res);
        },
        success: function(res) {
            console.log(res);
        }
    });
});

PHP

add_action('wp_ajax_uploadCompanyLogo', 'update_company_logo');

function update_company_logo() {
    $logo = $_POST['company_logo'];
    $attachment_id = media_handle_upload($logo, 0);
                
    echo $attachment_id;
}

Using this code, when I submit the form I get the following jQuery error in the console:

Uncaught TypeError: Illegal invocation
1
  • Do you have a code sandbox? In which line are you getting error? Commented Jul 13, 2020 at 16:36

1 Answer 1

2

Try to use a FormData in the javascript to properly send the data.

Something like that:

$('#company-logo-form').on('submit', function(e) {
    e.preventDefault();
    let logo = $('#logo-test').prop('files')[0]; // Since 'files' is array.
    let formData = new FormData(); // Create a new form.
    formData.append('action', 'uploadCompanyLogo');
    formData.append('company_logo', logo);

    $.ajax({
        url: ajax_url,
        type: 'POST',
        data: formData,
        contentType: false, // No content type headers.
        processData: false, // Do not process sent data.
        error: function(res) {
            console.log(res);
        },
        success: function(res) {
            console.log(res);
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.