带有文件上传的Wordpress表单通过Ajax提交 [英] Wordpress form with file upload submit with Ajax

查看:94
本文介绍了带有文件上传的Wordpress表单通过Ajax提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建表单并使用Ajax提交.因此,该页面不会重新加载.我对ajax的使用经验不多,我正在努力寻找尽可能多的信息.

I am trying to create form and submitting this with ajax. So the page wont reload. I don't have a lot of experience with ajax and I am trying to find as much information as I can.

现在在我的代码中,我可以不重新加载就发送表单.但是我有一个用于上传文件的字段.我知道这样做有点不同,我也找到了一些例子,但到目前为止还没有运气.例如在Wordpress中上载Ajax文件-无法传递FormData

Right now in my code I can sbmit form without reloading. But I have a field for uploading files. I know It is a bit different to do this and I also found some examples but so far no luck. For example Ajax file upload in Wordpress - can't pass FormData

现在我有这样的My Ajax代码:

Right now I have My Ajax code like this:

Ajax

(function($) {

jQuery(document).ready(function() {

    // when user submits the form
    jQuery(document).on('submit', '.form-assignment', function(event) {

        var error_elm = jQuery('.ajax-error');
        var response_elm = jQuery('.ajax-response')
       // var widgetId = grecaptcha.reset(container);
        error_elm.html('');
        response_elm.html('');

        // prevent form submission
        event.preventDefault();

        var form_elm = jQuery(this);

        var url = form_elm.data('url');
        var action = form_elm.data('action');
        var form_data = new FormData();

        var data = {
            action: action,
            form_data : form_data
        };

        // add loading message
        response_elm.html('Loading...');

        jQuery.ajax({
            type : 'POST',
            url : url,
            data : data,
            processData: false,
            contentType: false,
            enctype: 'multipart/form-data',
            dataType : 'json',
            async : true
        }).success(function(response) {

            error_elm.html('');
            response_elm.html('');

            if(response.status !== 'success') {
                // something went wrong
                if(response.message) {
                    error_elm.html(response.message);
                    return;
                }

                // don't know ?
            }

            // success!!

            // log data
            console.log(response);

            // display data
            response_elm.html(response.message);
            $("#form-assignment").trigger("reset");
            grecaptcha.reset();
        }).error(function(response) {
            error_elm.html('');
            response_elm.html('');

            error_elm.html(response.statusText);
        });
    });

});



})( jQuery );

我的表单:

 <div class="ajax-error" style="color: red;"></div>
    <form class="form-assignment" name="form_assignment" id="form-assignment"
          method="post" enctype="multipart/form-data"
          data-url="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ) ?>" data-action="form_submit1">
          <label>name:</label>
          <input type="text" name="customer-field-text"pattern="[a-zA-Z0-9 ]+" placeholder="<?php echo $field->label ?>" size="40"/>
          <label>file upload</label>
           <input type="file"  name="customer-field-upload" id="customer-field-upload"
                           multiple="false"/>
    </form>

现在这就是我走了多远.这不是我的完整表格,我已经添加了现时和其他要求的顺序设置.当我检查输入文件时,它一直显示错误消息,该字段为空.

Right now this is how far I got. This is not my full form I have already added nonce and other required settings for sequrity. When I check input file It keep displaying error message that the field is empty.

我的表单处理程序

function handle_form_submission (){
global $wpdb;
$response = array(
    'status' => 'error',
    'message' => '',
);


parse_str($_POST['form_data'], $form_data);

//global $error;
$error = new WP_Error();

    if (empty($_POST['customer-field-name'])  ) {
    $error->add('empty','Name is required.');
}

    if (empty($_POST['customer-field-upload']) && empty($_FILES["customer-field-upload"]["name"])) {
    $error->add('empty','select an file.');
}

if ( !empty( $error->get_error_codes() ) ) {
    $error_messages = $error->get_error_messages();

    $error = '';
    foreach($error_messages as $error_message) {
        $error .= '<p>'.$error_message.'</p>';
    }

    $response['message'] = $error;

    wp_send_json( $response );
    wp_die();
}
$name                 = sanitize_text_field( $form_data["customer-field-name"] );
$upload                 = sanitize_text_field( $form_data["customer-field-upload"] );


require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );

 media_handle_upload( 'customer_field_upload', $form_data['post_id'] );

}

    add_action( 'wp_ajax_form_submit1', 'handle_form_submission' );

    // ajax hook for non-logged-in users: wp_ajax_nopriv_{action}
    add_action( 'wp_ajax_nopriv_form_submit1', 'handle_form_submission' );

所以我的问题是我该怎么做,或者在我的ajax或表单处理程序中添加内容,以便在Ajax工作的情况下提交文件上传.任何熟悉的建议,建议或一些现有示例将不胜感激.我正在使用WordPress和Ajax进行练习,这是我的发展目标.

So My question is What can I do or add in my ajax or form handler to get file upload submit with Ajax working. Any suggestion, advice or some existing example that are familiar will be appreciated. I am practicing with WordPress and Ajax that is how far I got.

我已经尝试过使用FormData,但到目前为止仍然没有运气.

I have tried to use FormData but still no luck so far.

推荐答案

以下是一些使您提供的表单起作用的提示:

Here is some tips to make work your provided form:

表格:

<div class="ajax-error" style="color: red;"></div>
<form class="form-assignment" name="form_assignment" id="form-assignment" method="post" enctype="multipart/form-data"
      data-url="<?php echo esc_url(admin_url('admin-ajax.php')) ?>" data-action="form_submit1">
    <label>name:</label>
    <input type="text" name="customer-field-text" pattern="[a-zA-Z0-9 ]+" size="40"/>
    <label>file upload</label>
    <input type="file" name="customer-field-upload" id="customer-field-upload" multiple="false"/>
    <input type="submit" value="Submit" name="submit">
</form>

我从您的text输入中删除了placeholder="<?php echo $field->label ?>",因为它来自您未提供的自定义代码.

I removed placeholder="<?php echo $field->label ?>" from your text input, because it's coming from custom code, which you didn't provide.

Ajax.js :

jQuery(document).ready(function ($) {
    // when user submits the form
    jQuery(document).on('submit', '.form-assignment', function (event) {

        var error_elm = jQuery('.ajax-error');
        var response_elm = jQuery('.ajax-response');
        error_elm.html('');
        response_elm.html('');

        event.preventDefault();

        var form_elm = jQuery(this);

        var url = form_elm.data('url');
        var action = form_elm.data('action');
        var file = form_elm[0][1].files[0];
        var customer_field_text = form_elm[0][0].value;
        var form_data = new FormData();
        form_data.append('action', action);
        form_data.append('customer-field-upload', file);
        form_data.append('customer-field-name', customer_field_text);

        response_elm.html('Loading...');

        jQuery.ajax({
            type: 'POST',
            url: url,
            data: form_data,
            processData: false,
            contentType: false,
            cache: false
        }).success(function (response) {

            error_elm.html('');
            response_elm.html('');

            if (response.status !== 'success') {
                // something went wrong
                if (response.message) {
                    error_elm.html(response.message);
                    return;
                }

                // don't know ?
            }

            response_elm.html(response.message);
            $("#form-assignment").trigger("reset");

        }).error(function (response) {
            error_elm.html('');
            response_elm.html('');

            error_elm.html(response.statusText);
        });
    });

});

注意:您使用的是var form_elm = jQuery(this);,它将返回具有所有Form内容的jquery对象.这就是为什么我用它来访问输入信息.相反,您可以使用其名称,类,ID,占位符等访问表单输入.

NOTE: You're using var form_elm = jQuery(this);, which returns object of jquery with all Form content. That's why I used it for accessing input information. Instead you can access to form inputs with their name, class, id, placeholder and etc.

发生了什么变化:

  1. 删除了(function($) {}包装器,而是使用了jQuery(document).ready(function ($) {});.这只是为了说明.无需包装您的jquery就可以访问$.
  2. 我们正在从下面的输入行中获取文件和名称:

  1. removed (function($) {} wrapper and instead used jQuery(document).ready(function ($) {});. This is just for note. There is no need to wrapp your jquery to have access to $.
  2. We're getting file and name from inputs with lines below:

var file = form_elm[0][1].files[0];
var customer_field_text = form_elm[0][0].value;

  • 我们正在为WordPress添加action,并将带有其值的输入形式输入

  • We're adding action for WordPress and form inputs with their values into FormData:

    form_data.append('action', action);
    form_data.append('customer-field-upload', file);
    form_data.append('customer-field-name', customer_field_text);
    

    您可以在此处更改要发送的数组的名称.例如,我们将使用键customer-field-upload接收数组中的文件,并可以通过以下方式使用它:

    Here you can change the name of array we're sending. For ex., we will recieve file in the array with key customer-field-upload and can use it such way:

    $_FILES['customer-field-upload']
    

  • async : true:我们不需要此行.默认为为真. enctype: 'multipart/form-data',我们也不需要.
  • data: form_data,:我们仅使用一个form_data变量(FormData object)发送所有内容.
  • async : true: this line we don't need. It's true by default. enctype: 'multipart/form-data', we don't need, too.
  • data: form_data,: we are sending everything only using one form_data variable( FormData object ).
  • PHP 文件:

    1. 我没有使用add_action('wp_ajax_nopriv_form_submit1', 'handle_form_submission');,因为您提供的代码中没有与nonce相关的内容
    2. 您的$_POST将包含:

    1. I didn't use add_action('wp_ajax_nopriv_form_submit1', 'handle_form_submission'); because there is nothing related to nonce in your provided code
    2. Your $_POST will contain:

    Array
    (
       [action] => form_submit1 //action, which we used to send and accept Ajax request
       [customer-field-name] => some input value in the name field
    )
    

    您可以使用$_POST['customer-field-name']访问名称输入.

    You can access to name input using $_POST['customer-field-name'].

    您的$_FILES将包含:

    Array
    (
        [customer-field-upload] => Array
            (
                [name] => input file name
                [type] => input file type
                [tmp_name] => temp file
                [error] => 0 
                [size] => some size
            )
    
    )
    

    您可以使用$_FILES['customer-field-upload']


    编辑:附加功能,可添加带有多行代码的所有输入:


    Appended functional to add all inputs with several lines of code:

    表格:

    <div class="ajax-error" style="color: red;"></div>
    <form class="form-assignment" name="form_assignment" id="form-assignment" method="post" enctype="multipart/form-data"
          data-url="<?php echo esc_url(admin_url('admin-ajax.php')) ?>" data-action="form_submit1">
        <label for="customer-field-text">name:</label>
        <input type="text" name="customer-field-text" id="customer-field-text" pattern="[a-zA-Z0-9 ]+" size="40"/>
        <label>file upload</label>
        <input type="file" name="customer-field-upload" id="customer-field-upload" multiple="false"/>
        <label for="select">select:</label>
        <select name="carlist" id="select">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
        </select>
        <label for="email">email: </label>
        <input type="text" name="email" id="email">
        <input type="submit" value="Submit" name="submit">
    </form>
    

    Ajax.js:

    jQuery(document).ready(function ($) {
        // when user submits the form
        jQuery(document).on('submit', '.form-assignment', function (event) {
    
            var error_elm = jQuery('.ajax-error');
            var response_elm = jQuery('.ajax-response');
            error_elm.html('');
            response_elm.html('');
    
            event.preventDefault();
    
            var form_elm = jQuery(this);
    
            var url = form_elm.data('url');
            var action = form_elm.data('action');
            var file_input_name = jQuery('#form-assignment').find('input[type=file]').attr('id');
            var form_data = new FormData();
    
            form_data.append('action', action);
    
            jQuery.each(jQuery(':input:not([type=submit]):not([type=file])', '#form-assignment' ), function(i, fileds){
                form_data.append(jQuery(fileds).attr('name'), jQuery(fileds).val());
            });
            jQuery.each(jQuery(':input:not([type=submit]):not([type=text]):not([type=select])', '#form-assignment' )[0].files, function(i, file){
                form_data.append(file_input_name, file);
            });
    
            response_elm.html('Loading...');
    
            jQuery.ajax({
                type: 'POST',
                url: url,
                data: form_data,
                processData: false,
                contentType: false,
                cache: false
            }).success(function (response) {
    
                error_elm.html('');
                response_elm.html('');
    
                if (response.status !== 'success') {
                    // something went wrong
                    if (response.message) {
                        error_elm.html(response.message);
                        return;
                    }
    
                    // don't know ?
                }
    
                response_elm.html(response.message);
                $("#form-assignment").trigger("reset");
    
            }).error(function (response) {
                error_elm.html('');
                response_elm.html('');
    
                error_elm.html(response.statusText);
            });
        });
    
    });
    

    在这里,我们使用 Jquery迭代器将循环中的多个值添加到对象.这是示例,可以应用于复选框,文本区域等.

    Here we used Jquery iterator to add several values from the loop into the FormData object. This is example and can be applied for checkboxes, textareas and etc.

    这篇关于带有文件上传的Wordpress表单通过Ajax提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆