简体   繁体   中英

How to properly set up jQuery ajax to upload files in Wordpress?

I want the user to be able to upload html files using ajax from my custom editor block. Wordpress requires all ajax go through admin-ajax.php. My js code is in an external file registered and enqueued in Wordpress. Here is a Wordpress Codex instruction from https://codex.wordpress.org/AJAX_in_Plugins :

Separate JavaScript File

The same example as the previous one, except with the JavaScript on a separate external file we'll call js/my_query.js. The examples are relative to a plugin folder.

jQuery(document).ready(function($) {
    var data = {
        'action': 'my_action',
        'whatever': ajax_object.we_value      // We pass php values differently!
    };
    // We can also pass the url value separately from ajaxurl for front end AJAX implementations
    jQuery.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

With external JavaScript files, we must first wp_enqueue_script() so they are included on the page. Additionally, we must use wp_localize_script() to pass values into JavaScript object properties, since PHP cannot directly echo values into our JavaScript file. The handler function is the same as the previous example.

<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
    if( 'index.php' != $hook ) {
    // Only applies to dashboard panel
    return;
    }
        
    wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );

    // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
    wp_localize_script( 'ajax-script', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}

Here is my PHP:

if (isset ( $_POST["test"] ) ){
    echo 'test working';
}
if ( isset ( $_FILES["renee_wip_upload"] ) ){
    echo 'test2';
}

And here is my js function:

function fileSubmit(e) {
    e.preventDefault();
    if(typeof(files2) !== "undefined"){
    //ajax using post() works fine which means the php side is OK
        renee_wip_ajax_object.braft_wip_upload_value = 'test';
        var data2 = {
            'action': 'renee_wip_block_ajax',
            'test': renee_wip_ajax_object.braft_wip_upload_value
        };
        jQuery.post(renee_wip_ajax_object.ajax_url, data2, function(response) {
            console.log('response test: ', response);
        }).fail(function(response) {
            console.log('Error: ' + response.responseText);
        });

        //It seems $_FILES never gets populated
        data = new FormData();
        data.append('action', 'renee_wip_block_ajax');
        for (var i = 0; i < files2.length; i++) {
            var file = files2[i];
            data.append('renee_wip_upload[]', file, file.name);
        }
        jQuery.ajax({
            success: function(data){
                console.log('data: ', data);
            },
            error: function(err){
            throw err;
            },
            type: "post",
            url: renee_wip_ajax_object.ajax_url,
            data: data,
            dataType: "html",
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false,
        }).done(function(msg){
            console.log('done: ', msg);
        }).fail(function(err){
          throw err;
        });
    }
}

Man, I am blind as hell. It was: data.append('braft_wip_upload[]', file, file.name); but should be: data.append('renee_wip_upload[]', file, file.name); I even corrected the mistake in edit, but forgot to do it in my code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM