Загрузка файла SQL с использованием jQuery и Ajax - PullRequest
0 голосов
/ 20 октября 2018

Я столкнулся с очень глупой проблемой и не смог найти правильного решения и его основ.Я пытаюсь загрузить файл с расширением .sql через jquery и ajax, используя загрузочный модал в плагине WordPress, но он не работает как-то, как и дает 400 плохой запрос запроса

Пожалуйста, имейтеПосмотрите и помогите мне устранить проблему.

Модальное изображение enter image description here Модальный код

<div class="modal" id="testrestoremodal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modal-heading-auto"><?php _e('Restore', 'test'); ?></h4>
                <button type="button" class="close fui-cross" data-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="post" id="test_restore_form" enctype="multipart/form-data" style="width: 100% ! important">
                    <input type="hidden" name="test_restore_database">

                    <input type="hidden" name="action" value="test_restore_back_file">
                    <input id= "restore_nonce" type="hidden" name="restore_nonce" value="<?php echo wp_create_nonce(basename(__FILE__)) ?>"/>
                    <div class="row" style="margin: 5px 0px 5px 0px !important;">
                        <div class="col-sm-12">
                            <div class="form-group">
                                <div class="fileinput fileinput-new" data-provides="fileinput">
                                    <div class="input-group">
                                        <div class="form-control uneditable-input" data-trigger="fileinput">
                                            <span class="fui-clip fileinput-exists"></span>
                                            <span class="fileinput-filename"></span>
                                        </div>
                                        <span class="input-group-btn btn-file">
                                            <span class="btn btn-default fileinput-new" data-role="select-file">Select file</span>
                                            <span class="btn btn-default fileinput-exists" data-role="change"><span class="fui-gear"></span>&nbsp;&nbsp;Change</span>
                                            <input type="hidden"><input name="backup_restore_file" onChange="validate(this.value)" type="file" id="backup_restore_file">
                                            <a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput"><span class="fui-trash"></span>&nbsp;&nbsp;Remove</a>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" id="restore_plugin_backup"><?php _e('OK', 'test'); ?></button>
                        <button type="button" class="btn btn-danger" data-dismiss="modal"><?php _e('Cancel', 'test'); ?></button>
                    </div>
                </form>
            </div>

        </div>
    </div>
</div>

Я называю мой модал вот так

/* Restore Plugin Backup */
jQuery(document).on('click', '#test_restore_database_popup', function () {
    jQuery('#testrestoremodal').modal('show');
});

и код действия wordpress: -

<code>add_action('wp_ajax_test_restore_back_file', 'test_restore_backup_data');
    function test_restore_backup_data() {
    echo '<pre>';
        print_r($_POST);
        echo '
';if (isset ($ _ POST ['restore_nonce']) && isset ($ _ POST ['test_restore_database'])) {test_restore_backup ($ _ POST);} умереть();}

И его ошибка неверного запроса возврата 400 всегда.

И мой код js для загрузки файла: -

jQuery(document).ready(function () {
    jQuery('#restore_plugin_backup').click(function () {
        var form_data_restore = new FormData();        
        form_data_restore.append('backup_file', jQuery("#backup_restore_file")[0].files[0]);

        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: form_data_restore,
            contentType:false, // this
            dataType: false,
            cache:false,
            success: function (response) {
                alert(response);
            }
        });
    });
});

Пожалуйста, помогите мне.

Ответы [ 2 ]

0 голосов
/ 23 октября 2018

После проверки множества вещей я получил решение загрузить любой файл, используя этот код

jQuery(function () {
    jQuery('#test_import_url_button').click(function () {
        var importdata = new FormData();
        var importfile = jQuery('#import_url_data')[0].files[0];
        importdata.append('import_file', importfile);
        importdata.append('import_file_name', importfile.name);
        importdata.append('action', 'wpretarget_import_url');
        jQuery.ajax({
            url: ajaxurl,
            data: importdata,
            processData: false,
            contentType: false, // this
            dataType: 'json',
            type: 'POST',
            success: function (response) {
                alert(response);
            }
        });
    });
});

И эта статья поможет мне устранить ошибку

https://www.sitepoint.com/enabling-ajax-file-uploads-in-your-wordpress-plugin/

0 голосов
/ 20 октября 2018

Сначала вы отправляете wp nonce с помощью ajax, как это

add_action( 'wp_enqueue_scripts', 'my_scripts' );
function my_scripts(){
$url = trailingslashit( plugin_dir_url( __FILE__ ));
wp_enqueue_script('my-script-handle', $url . "assets/script.js", array('jquery'), true);
wp_localize_script('my-script-handle', 'frontEndAjax', array(  'ajaxurl' => admin_url( 'admin-ajax.php' ),  'nonce' => wp_create_nonce('ajax_nonce') ));
}

, затем вызываете ajax, как этот

var data = {
'file': JSON.parse(file_data),
'action': 'my_ajax_function',
'nonce': frontEndAjax.nonce,
} ;
jQuery.ajax({
url:  frontEndAjax.ajaxurl,
type: 'post',
datatype: 'json',
data: data,
success: function (response) {

},error: function (response) {

}
});

, затем получаете ответ и все, что вы можете сделать с ответом.

...